Remove Nth Node From End of List
题目
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.
思路
主要是要将指针指到链表从末尾向前数的第n+1个结点P,知道P结点,就能通过P->next=p->next->next。不过要注意一种特定情形,删除的节点刚好是首结点。可以通过定义头结点来解决。通过两个指针来解决,一个指针先行n+1步,然后再两个指针同时移步。
解题
c++版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| * 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 dummy(-1); dummy.next=head; ListNode *p,*q; p=&dummy; q=&dummy; while(n--) p=p->next; p=p->next; while(p and q){ p=p->next; q=q->next; } q->next=q->next->next; return dummy.next; } };
|
python版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Solution: def removeNthFromEnd(self, head, n): dummy=ListNode(0) dummy.next=head p=dummy q=dummy for i in range(n+1): p=p.next while(p and q): p=p.next q=q.next q.next=q.next.next return dummy.next
|