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个元素,并返回修改后的链表。
要求: 只经过一次遍历完成上述操作。
经典面试题,找到一个链表的倒数第N个元素的衍伸。 在本题中需要额外的记录第N个元素的上一个元素,用于元素删除。
寻找链表的倒数第N个元素,设置两个指针,分别从链表的头部出发,一个先遍历N个元素, 然后两个指针同时向后遍历,当前一个指针到达链表的尾部时,后一个指针则到达第N个元素。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *removeNthFromEnd(ListNode *head, int n) { 12 ListNode *pre,*first,*last; 13 ListNode ans(0); 14 pre=first=last=head; 15 ans.next=pre; 16 for(int i=0;i<n;i++) 17 first=first->next; //find faster pointer 18 19 while(first!=NULL) 20 { 21 first=first->next; 22 pre = last; 23 last=last->next; 24 } 25 pre->next = last->next; 26 if(last==head) return head->next; 27 else return ans.next; 28 } 29 };
转载请注明出处 http://www.cnblogs.com/double-win/ 谢谢!