"Huawei OJ" "035-output one-way link list of the penultimate K nodes"

Source: Internet
Author: User

"Huawei OJ" "Algorithm Total chapter" "Huawei OJ" "035-Output unidirectional link list of the penultimate K nodes" "Project download" title description
输入一个单向链表,输出该链表中倒数第k个结点,链表的倒数第0个结点为链表的尾指针。
Enter a description
输入说明1 输入链表结点个数2 输入链表的值3 输入k的值
Output description
输出一个整数
Input example
8 1 2 3 4 5 6 7 8 4
Output example
4
Algorithm implementation
ImportOrg.omg.SendingContext.RunTime;ImportJava.util.List;ImportJava.util.Scanner;/** * Author: Wang Junshu * date:2015-12-24 16:10 * All rights Reserved!!! */ Public  class Main {     Public Static void Main(string[] args) {Scanner Scanner =NewScanner (system.in);//Scanner Scanner = new Scanner (Main.class.getClassLoader (). getResourceAsStream ("Data.txt"));         while(Scanner.hasnext ()) {intn = scanner.nextint (); ListNode head =NewListNode (0); ListNode prev = head; while((--n) >=0) {Prev.next =NewListNode (Scanner.nextint ());            prev = Prev.next; }intK = Scanner.nextint ();        System.out.println (Findkthtotail (head, k));    } scanner.close (); }/** * Find the bottom k node, assuming K is valid * * @param head * @param k * @return  */    Private StaticListNodeFindkthtotail(ListNode Head,intk) {ListNode prev = head; while(--k >=0&& prev! =NULL) {prev = Prev.next; }//Description K has exceeded the length of the list        if(prev = =NULL) {Throw NewRuntimeException ("k="+ K +"not legal."); }//commented out is the correct answer//while (prev! = null) {//prev = Prev.next;//head = Head.next;//        }        //If starting from 0, that is, the first one at the end of the list is the bottom No. 0, then the following is correct.         while(Prev.next! =NULL) {prev = Prev.next;        head = Head.next; }returnHead }Private Static  class listnode {        intV        ListNode Next; ListNode (intV) { This. v = v; }@Override         PublicStringtoString() {return ""+ V; }    }}

"Huawei OJ" "035-output one-way link list of the penultimate K nodes"

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.