標籤:java 微軟面試100題
歡迎轉載,轉載請務必註明出處:http://blog.csdn.net/alading2009/article/details/45037001
第13題:輸入一個單向鏈表,輸出該鏈表中倒數第K個結點。鏈表的倒數第0個結點為鏈表的尾指標。
考慮如何在程式執行中保留K這個資訊,這兒使用兩個座標,要讓這兩個座標之間相距K個距離,於是當前一個座標到達尾指標時,後一個座標恰好與尾相距K個結點距離。
代碼
package test013;import test007.Node;/** * Created by cq on 2015/4/11. * 第13題:輸入一個單向鏈表,輸出該鏈表中倒數第K個結點。鏈表的倒數第0個結點為鏈表的尾指標。 */public class Test013 { public static Node getLastKNode(Node list, int k){ if (list == null || k < 0){ return null; } Node anchor = list; int index = 0; while (list != null){ //在anchor和list之間拉開k個結點的距離 if (index < k){ list = list.getNext(); index++; continue; } anchor = anchor.getNext(); list = list.getNext(); }// //鏈表長度不到k// if (index < k){// anchor = null;// } return anchor; } public static void main(String[] args){ Node list = new Node(5); Node node4 = new Node(4); Node node3 = new Node(3); Node node2 = new Node(2); Node node1 = new Node(1); list.setNext(node4); node4.setNext(node3); node3.setNext(node2); node2.setNext(node1); System.out.println("倒數第2個結點是:"+getLastKNode(list, 2).getData()); System.out.println("倒數第4個結點是:"+getLastKNode(list, 4).getData()); System.out.println("倒數第7個結點是:"+getLastKNode(list, 7).getData()); System.out.println("倒數第10個結點是:"+getLastKNode(list, 10).getData()); }}
執行結果
Connected to the target VM, address: ‘127.0.0.1:2218‘, transport: ‘socket‘倒數第2個結點是:2倒數第4個結點是:4倒數第7個結點是:5倒數第10個結點是:5Disconnected from the target VM, address: ‘127.0.0.1:2218‘, transport: ‘socket‘Process finished with exit code 0
第13題:取鏈表中倒數第K個結點