Leetcode Remove Nth Node from End of List

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.