02:倒數鏈表第k個數值

倒數鏈表第k個數值

注意事項:
1.head不爲null
2.k>0,k<鏈表的長度
方法採用雙指針方式

public class Offer02 {

    public static void main(String[] args) {
    	//創建一個鏈表
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = null;

        int i = bottomNumber(node1, 5);
        System.out.println(i);
    }


    public static int bottomNumber(ListNode head, int k){
        //1.判斷
        if(head==null||k==0)return -1;

        ListNode front = head;
        ListNode behind = head;

        //2.先讓front走k-1步
        for(int i = 0;i<k-1;i++){
            //k比鏈表的長度要長
            if(front.next==null)return -1;
            front = front.next;
        }

        //3.front和behind一起走到結尾
        while(front.next != null){
            front = front.next;
            behind = behind.next;
        }

        return behind.val;
    }
}

class ListNode {
    int val;
    ListNode next;// 下一個鏈表對象

    public ListNode(int val) {
        this.val = val;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章