Delete the nth vertex from the list

Source: Internet
Author: User
One-time Traversal Algorithm

Algorithm

The algorithm can be traversed only once. We can use two pointers instead of one. The first pointer moves n + 1 step forward from the beginning of the List, and the second pointer starts from the beginning of the list. Now, the two pointers are separated by N nodes. We keep this constant interval by moving the two pointers forward at the same time until the first pointer reaches the last node. The second Pointer Points to the nth node starting from the last knot point. Relink the node referenced by the second pointernextThe Pointer Points to the next node of the node.

/**
* Definition for singly-linked list.
* Public class listnode {
* Int val;
* Listnode next;
* Listnode (int x) {val = x ;}
*}
*/
Class solution {


Public listnode removenthfromend (listnode head, int N ){
Listnode dummy = new listnode (0 );
Dummy. Next = head;
Listnode first = dummy;
Listnode second = dummy;
N = n + 1;
While (n! = 0 ){
First = first. Next;
N --;
}
While (first! = NULL ){
First = first. Next;
Second = second. Next;
}
Second. Next = second. Next. Next;

Return dummy. Next;
}
}

Delete the nth vertex from the 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.