Sword refers to the penultimate K node in the offer-chain list.

Source: Internet
Author: User

Title Description

Enter a list to output the last K nodes in the linked list.

 Public classTest {classListNode {intvalue;        ListNode Next;  PublicListNode (intvalue) {             This. Value =value; }    }         Public Static voidMain (string[] args) {Test T=NewTest (); ListNode Node1= T.NewListNode (1); ListNode Node2= T.NewListNode (2); ListNode Node3= T.NewListNode (3); ListNode Node4= T.NewListNode (4); ListNode Node5= T.NewListNode (5); ListNode Node6= T.NewListNode (6); ListNode Node7= T.NewListNode (7); Node1.next=Node2; Node2.next=Node3; Node3.next=Node4; Node4.next=Node5; Node5.next=Node6; Node6.next=Node7; Node7.next=NULL; ListNode Kthnode= T.findkthtotail (Node1, 2);    System.out.println (Kthnode.value); }        /*** One traversal to find the bottom k node *@paramHead *@paramk K starting from 1 *@return     */     PublicListNode Findkthtotail (ListNode head,intk) {//the list entered cannot be empty, K is greater than 0:k starting from 1, less than 0 is meaningless        if(Head = =NULL|| K <= 0)return NULL; ListNode Pforward=Head; ListNode Pbehind=NULL; //The first pointer moves forward k-1.         for(inti=0; i<k-1; i++) {            //if K is greater than the number of nodes, next May point to NULL, return null            if(Pforward.next = =NULL)                return NULL; Pforward=Pforward.next; }        //The second pointer does not move temporarilyPbehind =Head; //Two pointers move together//when the previous pointer traverses to the last node, a pointer to the bottom of the K-node         while(Pforward.next! =NULL) {Pforward=Pforward.next; Pbehind=Pbehind.next; }        returnPbehind; }}  

Sword refers to the penultimate node of the offer-chain 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.