Remove Nth Node from End of List

Source: Internet
Author: User

1. Problem

Removes the last nth node of the linked list and returns the list header. One traversal completes

return Its head. For example,   1->2->3->4->5, and n = 2.    1->2->3->5 do the in one pass.
2. Solution

With two pointers:

    • P: The previous node pointing to the possible point of omission;
    • Q:q-p = n;

For ease of handling, add an empty node in front of the linked list. The code is as follows:

1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7  * }8  */9  Public classSolution {Ten      PublicListNode Removenthfromend (ListNode head,intN) { One         if(Head = =NULL ) A             returnhead; -         //Create a new head node so the we can always remove P.next -ListNode Newhead =NewListNode (0); theNewhead.next =head; -ListNode p = newhead;//Point to the previous node before to-be-deleted node -ListNode q = head;//q-p = n; -         intCount = 1;//To find the first satisfied Q; +          for(; q.next!=NULL&& count<n; count++, q =q.next); -         //The to-be-deleted node exists +         if(Count = =N) { A              while(Q.next! =NULL ){ atp =P.next; -Q =Q.next; -             } -P.next =P.next.next; -         } -         returnNewhead.next; in     } -}

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.