"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"