Remove Nth Node from End of List

Source: Internet
Author: User

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

Remove Nth Node from End of List

Given A linked list, remove the nth node from the end of the list and return its head.

For example,

   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.

Title: Delete the last nth node of the linked list.

How does the countdown work? Using dummy nodes and two pointers P1 and P2,p1 first n steps, then P1 and P2 go together, when P1.next is empty, when the entire list is gone, P2.next is the reciprocal nth node to be deleted.

(Set the list of M nodes, you need to find the penultimate nth, then P2 need to go forward and through the M-n node, the next is the desired nth node, the positive sequence of m-n step how to control, is through the P1 this pointer)

1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8     #@param {ListNode} head9     #@param {integer} nTen     #@return {ListNode} One     defremoventhfromend (self, head, N): Adummy=listnode (0) -dummy.next=Head -P1=p2=dummy#p1,p2 simultaneous dummy departure the          forIinchRange (N):#P1 go first n step -p1=P1.next -          whileP1.next:#p1,p2 go at the same time, until P1 walk through the list -p1=P1.next +P2=P2.next -P2.next=p2.next.next#Delete the p2.next at this time +         returnDummy.next

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.