Leetcode-remove Nth Node from End of List

Source: Internet
Author: User

Given A linked list, remove the nth node fromThe end of list andreturnIts head. For example, Given linked list:1-2-3-4-5, and n =2. After removing the second node fromThe end, the linked list becomes1-2-3-5. Note:given n would always be valid. Try to Do  This inchOne pass.

Classic question. Double pointer, a pointer to go first n step, then two synchronized walk, until the first to go to the end, the second pointer is to delete the node. The only thing to note is the processing of the head node, for example,
1->2->null, n = 2; At this point, the head node is to be deleted.

/** * Definition for singly-linked list. * public class ListNode {*     int val; *     ListNode Next; *     listnode (int x) {val = x;}}} */public class Soluti On {public    ListNode removenthfromend (listnode head, int n) {        if (head = = null)            return null;         ListNode fast = head;        ListNode slow = head;         for (int i=0; i<n; i++) {            fast = Fast.next;        }         If remove the first node        if (fast = = null) {            head = Head.next;            return head;        }         while (fast.next! = null) {            fast = Fast.next;            slow = Slow.next;        }         Slow.next = Slow.next.next;         return head;    }}

  

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.