劍指offer——鏈表中倒數第k個結點

題目描述

輸入一個鏈表,輸出該鏈表中倒數第k個結點。要求只遍歷一次鏈表

思路:當第一個指針forward走到k-1位置的時候,第二個開始一起右移,直到結束。

public class FindKthNode {
     public static ListNode FindKthToTail(ListNode head,int k) {
            if(head==null||k==0){
                return null;
            }
            //一前一後兩個指針
            ListNode forward = head;
            ListNode behind = head;

            for(int i = 0;i<k-1;i++){
                if(forward.next!=null){
                forward = forward.next;
                }else{
                    //k比整個鏈表長度還要大
                    return null;
                }
            }

            while(forward.next!=null){
                forward = forward.next;
                behind = behind.next;
            }

            return behind;

        }

     public static void main(String[] args){
         ListNode a = new ListNode(1);
         ListNode b = new ListNode(2);
         ListNode c = new ListNode(3);

         a.next = b;
         b.next = c;

         System.out.println(FindKthToTail(a, 2).val);


     }
}

這裏寫圖片描述

發佈了80 篇原創文章 · 獲贊 141 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章