Leetcode remove Nth node from End of List removes the last n nodes

Source: Internet
Author: User

Topic:

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

For example,

   1->2->3->4->5  N = 2.   1->2->3->5.

Note:
Given n would always be valid.
Try to do the in one pass.

Translation:

Give you a list of the last nth nodes to remove.

Ideas:

The difficulty of this problem is also OK, is some of the details of the aspect, the first possible link list on a node. The second possibility is that the first node is deleted. The last is the connection to the node after the node is deleted.

Code:

Public ListNode Removenthfromend (listnode head, int n) {         if (head==null| | (Head.next = = null && n ==1))        return null;                ListNode p = head;        ListNode q = head;        ListNode pre = head;        while (n!=1)        {        q = q.next;        n--;        }        while (Q.next!=null)        {            pre = P;        Q = q.next;        p = p.next;        }        if (Pre.next = = p.next)            head = Head.next;        else             pre.next = P.next;        return head;            }
I used the method is two pointer p,q,q first traverse to the position of n-1, and then the two pointers traverse backwards at the same time, until Q to the end, at this time p should be deleted. At the same time, a pointer points to the previous one of P.

If P and pre point to the same node, the first element is deleted at this point. Because of the last q.next==null, this is as long as the head node points to his next point.

If P and pre are not equal, the P is deleted directly

Leetcode remove Nth node from End of List removes the last n nodes

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.