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.tag: linked-list, two pointers
用两个指针(快指针和慢指针)。
快指针先往前走n步,然后两个指针一起走,直到快指针到链表尾。
要注意n=length of list 的情况,也即要删掉链表里的第一个元素;还有要确定删掉链表中的某个元素时,实际上你需要将指针停在该元素的前一个元素,再进行删除。当然你也可以停到要删除的那个元素,再把下一个元素的value拷贝到该元素中,删除下一个元素,当然这是后话。
/** * 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) { ListNode * p, * q; p = q = head; while(n--){ p = p->next; } if(p == NULL){ return head->next; } while(p->next != NULL){ p = p->next; q = q->next; } q->next = q->next->next; return head; } };