第13題:取鏈表中倒數第K個結點

來源:互聯網
上載者:User

標籤: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個結點

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.