19. Remove Nth Node From End of List
problem description
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
algorithm thought
删除倒数第n个链表中的节点。链表不像数组,不能直接按index访问。所有人第一次做这种题肯定是想先遍历一遍得出长度,然后在删除倒数第n个。
但是链表找第倒数第几个节点有个小技巧,就是前后指针。比如这里的倒数第n个节点,我们首先让前指针先走n步,然后后指针和前指针一起行动。当前指针到终点的时候,后指针这时候正好在倒数第n个节点。这样就能实现一边遍历就能删除节点。
同样还有一种快慢指针,多用于求链表中点的。快慢指针都是从head点出发,一个每次走两步一个每次走一步,当快指针到tail节点的时候,慢指针正好在中点。
code
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    public:
    ListNode* removeNthFromEnd(ListNode* head, int n)
    {
        ListNode* tmp=new ListNode(-1);
        tmp->next=head;
        ListNode* second=tmp;
        while(--n){
            head=head->next;
        }
        while(head->next){
            head=head->next;
            second=second->next;
        }
        second->next=second->next->next;
        return tmp->next;
    }
};algorithm analysis
一次遍历,时间复杂度O(n)
Last updated