List of the penultimate K-Points of the list-Sword point offer

Source: Internet
Author: User

List of the last K nodes in the list of topics description

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

Ideas
    1. The linked list is traversed with two pointers, and two pointers are separated by K nodes, and the pointer to the first step goes to the K-node when it is finished.
    2. Some points to be aware of
      • Linked list may be empty, return null
      • K value may be 0, return null
      • The node of the linked list may not be enough k to return null
Code
/*PublicClass ListNode {int Val; ListNodeNext =Null ListNode (int val) {this.val = val;}} */PublicClass Solution {Public ListNode Findkthtotail (ListNode head,int k) {if (head = =null | | K = =0) {returnnull;} ListNoderight = head;for (int i =0; i < K-1; i++) {if (right. next! = null) {right = right. next;} else {return null;}} ListNode left = Head; while (right. Next! = null) {left = left.next; right = right. Next;} return left;}            

List of the last K nodes in the list-Sword point offer

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.