High-quality code-the penultimate K-node in a linked list

Source: Internet
Author: User

Title Description:

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

Ideas:

First check the legitimacy of the parameters, Head==null or the number of nodes less than K directly return NULL.

Let head advance k-1 step, ans points to the head node, then head forward one step, ans also step forward. When the head reaches the last node, ans points to the reciprocal K-node. Time complexity O (n).

Solve:

1 /*2 Public class ListNode {3 int val;4 ListNode next = null;5 6 listnode (int val) {7 this.val = val;8     }9 }*/Ten  Public classSolution { One      PublicListNode Findkthtotail (ListNode head,intk) { A         -ListNode ans =head; -          the         if(Head = =NULL|| K < 1) { -             return NULL; -         } -         inti =K; +         //head forward first k-1 node -          while(i > 1 && head.next! =NULL) { +Head =Head.next; Ai--; at         } -         //Insufficient number of nodes -         if(I! = 1) { -             return NULL; -         } -          in          while(Head.next! =NULL) { -Head =Head.next; toAns =Ans.next; +         } -         the         returnans; *          $     }Panax Notoginseng}

High-quality code-the penultimate K-node in a 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.