LeetCode 19 Remove Nth Node From End of List Remove the Nth Node, leetcodenth

Source: Internet
Author: User

LeetCode 19 Remove Nth Node From End of List Remove the Nth Node, leetcodenth

Question:

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.

Translation:

Give you a linked list and remove the nth last node.

Ideas:

The difficulty of this question is okay, that is, some details. First, the linked list may be a node. The first node may be deleted. The last step is to delete the node connection 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 am using two pointers, p, q, and q, first traverse to the n-1 position, and then both pointers traverse backward at the same time until q ends. At this time, p should be deleted. At the same time, a pointer points to the first one of p.

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

If p and pre are different, delete p directly.

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.