Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

 

思路一: 取到 整个link的长度l,然后移删除第l-n 个节点。

思路二:取两个指针,front和back,front优先于back n 步,当front指向最后一个节点时,back指向从后数n+1节点,然后删除第n个节点。

 

 

注意code中使用了dummy节点,避免了如果删除head节点的复杂逻辑判断。也避免了front指向NULL的情况,非常好用,屡试不爽。

class Solution {
    public:
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            ListNode dummy(-1);
            dummy.next = head;
            ListNode* front = &dummy;
            ListNode* back = &dummy;
    
            while(n)
            {   
                front = front->next;
                n--;
            }   

            while(front->next)
            {   
                front = front->next;
                back = back->next;
            }   

            back->next = back->next->next;
            return dummy.next;

        }   
};

 

相关文章:

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