[Lintcode] Remove Nth Node from End of List

Source: Internet
Author: User

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.

Example

Given linked List:1->2->3->4->5->null, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5->null.

Note

The minimum number of nodes in list is n.

Challenge

O (N) time

Solution:

Stupid method is to walk again, determine the length of the list, and then go through the length of the len-n, but asked O (n) to use two pointers, the first pointer to walk N, the second to go, when the first pointer has reached the end, the second pointer with a natural difference N, However, when you delete the list node, you need to record the point in front of node before deleting it.

Code:

/*** Definition for ListNode. * public class ListNode {* int val; * ListNode Next; * ListNode (int val) {* This.val = val; * This.next = null; *     } * } */  Public classSolution {/**     * @paramhead:the first node of linked list. * @paramN:an Integer. * @return: The head of linked list. */ListNode Removenthfromend (ListNode head,intN) {if(Head = =NULL|| N < 1){            returnHead; } ListNode Dummy=NewListNode (0); Dummy.next=Head; ListNode Predel=dummy;  for(inti = 0; I < n; i++){            if(Head! =NULL) {Head=Head.next; }        }         while(Head! =NULL) {Head=Head.next; Predel=Predel.next; } Predel.next=PreDel.next.next; returnDummy.next; }}
View Code

[Lintcode] 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.