Delete the penultimate K node in a single-linked list

Source: Internet
Author: User

Idea 1: Two pointers P1, p2, p1 traverse from the beginning, when the P1 reaches the K-node, p2 begins; When P1 reaches the last node in the list, p2 refers to the node in the list that is the reciprocal K-node.

 Public classnode{ Public intdata;  PublicNode Next;  PublicNode (intdata) {        This. data =data; }         PublicNode Removelastknode (node head,intk) {              if(Head = =NULL|| K < 1){            returnHead; } Node p1=Head; Node P2=Head; intnum = 1;  while(P1.next! =NULL&& Num <k) {         ++num; P1=P1.next; }               while(P1.next! =NULL) {P1=P1.next; P2=P2.next; } P2.next=P2.next.next; returnHead; }}

Train of thought 2: Time complexity O (n), Spatial complexity O (1).

1> If the linked list is empty or K < 1, return directly;
2> chain list from head to tail, each move one step, k value minus 1;

3> k > 0, there is no reciprocal K-node, return to the entire list;

If k = 0, the head node is the reciprocal K-node, and the head pointer is returned;

If k < 0, go from the beginning to find the node to delete the previous node, each move to let the K value plus 1, when k=0, the pointer value to the node is to delete the node of the previous node.

 PublicNode Removelastkthnode (node head,intlastkth) {                if(Head = =NULL|| Lastkth < 1){            returnHead; } Node P=Head;  while(P! =NULL) {lastkth--; P=P.next; }                if(lastkth = = 0) {Head=Head.next; }                if(Lastkth < 0) {p=Head;  while(++lastkth! = 0) {p=P.next; } P.next=P.next.next; }        returnHead; }

Delete the penultimate K node in a single-linked 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.