Given A linked list, remove the nth node from the end of the 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 would always be valid.
Try to do the in one pass.
Solution:
Because The linked list has no knowledge about the previous nodes and we have to provide such information.
The difference between the final node and the To-be-delete node are N, hence we can utilize this information.
? Front pointer points to the node which are N step away from the To-be-delete node
? rear pointer points to the To-be-delete node.
The algorithms is described as below:
? First driving front pointer N step forward.
? Secondly, move the 2 pointers 1 step ahead till the front pointer reach the end simultaneously, which'll cause the rear Pointer points to the previous node of the the To-be-delete node.
?
Finally, jump the Rear->next node by Rear->next = Rear->next->next.
The following code has a slight question:
http://bbs.csdn.net/topics/391029228
Class Solution {Public:listnode*removenthfromend(ListNode*head,intN) {ListNode New_head (-1); New_head.Next= head; ListNode*front= &new_head,*rear= &new_head; for(inti =0; I < n; i++) Front = front->Next; while(front->Next! = NULL) {front = front->Next; Rear = rear->Next; } ListNode*tmp= rear->Next; Rear->Next= rear->Next-Next;Deletetmp Head = New_head.Next;returnHead }};
Python solution:
# Definition for singly-linked list.# class ListNode:# def __init__ (self, x):# self.val = x# self.next = None class solution: # @param {listnode} head # @param {integer} n # @return {ListNode} def Removenthfromend ( Self, head, N):Dummyhead =ListNode(0) Dummyhead.Next= Head Slow = fast = Dummyhead forIinchRange (N):Fast = fast.Next whileFast andFast.Next:Fast = fast.Nextslow = slow.NextSlow.Next= Slow.Next.Next returnDummyhead.Next
Leetcode Remove Nth Node from End of List