删除链表的倒数第n个元素

- -开始感觉先统计有多少个,然后再计算出倒数第n个是正数第多少个。

但是!

题目说 one pass。。。

那么,这样,用两个直指针。p,q

p先跑n步,然后q和p一起跑,那么p跑到最后,q就正好在倒数第n个上面了。。。

 

做了这么多单链表的题了,我一前有个很不好的习惯,就是链表头步知道怎么处理,一般都是单独处理T_T

看了别人的代码,好多都是建立一个不用的头。。。然后真正的头在next里面。。。这样代码要少了单独处理头的那部分T_T

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        ListNode* dumy = new ListNode(0);
        dumy->next = head;
        ListNode* p = dumy;
        ListNode* q = dumy;
        for(int i = 0 ; i < n ; i++) p = p -> next; 
        while(p -> next != NULL){
            p = p -> next;
            q = q -> next;
        }
        q -> next = q -> next -> next; //下一个被删除,木有delete
        return dumy->next;
    }
};

  

相关文章:

  • 2022-02-24
  • 2021-11-15
  • 2022-12-23
  • 2021-08-02
  • 2022-12-23
猜你喜欢
  • 2021-09-07
  • 2021-10-27
  • 2021-11-14
  • 2021-07-11
  • 2022-02-24
  • 2021-09-15
  • 2022-02-16
相关资源
相似解决方案