Leetcode | #19 Remove Nth Node from End of List

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.


Ideas:

    • Count the number of nodes first, and change the number of count-n number of next to count-n-2.
    • The topic requires the best to traverse, that is mathematically clever, two pointers, first to go N steps, and then start and second at the same time, until the next is empty, then the second next to next
public class Removenthfromend {public class ListNode {int val; ListNode Next; ListNode (int x) {val = x;    next = null;}} /*//first count the number of nodes count, the number of count-n number of the next change to the number of count-n-2 public ListNode removenthfromend (listnode head, int n) {int count = 1; ListNode temp = Head;while (Temp.next! = null) {count++;temp = Temp.next;} int i = count-n;if (i = = 0) {return head.next;} temp = Head;while (i > 1) {temp = temp.next;i--;} Temp.next = Temp.next.next;return head;    } *///the topic requires the best to traverse, that is, mathematically clever, two pointers, first to go n steps,//and second at the same time walk, until the first next is empty, the second next change to next Nextpublic ListNode Removenthfromend (listnode head, int n) {ListNode first = head, second = head;for (int i=n; i>0; i--) {first = he Ad.next;} if (first = = null) {return first;} while (first.next! = null) {first = First.next;second = Second.next;} Second.next = Second.next.next;return head;    }}


Leetcode | #19 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.