劍指offer十四之鏈表中倒數第k個結點
阿新 • • 發佈:2017-10-01
gif img https question pla last 代碼 鏈表 ||
一、題目
輸入一個鏈表,輸出該鏈表中倒數第k個結點。
二、思路
兩個指針,先讓第一個指針和第二個指針都指向頭結點,然後再讓第一個指正走(k-1)步,到達第k個節點。然後兩個指針同時往後移動,當第一個結點到達末尾的時候,第二個結點所在位置就是倒數第k個節點了。
三、代碼
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { publicView CodeListNode FindKthToTail(ListNode head,int k) { if(head==null || k<=0){ return null; } ListNode pre=head; ListNode last=head; for(int i=k-1;i>0;i--){ //移動k-1步,移動到第k個節點 if(last.next!=null){ last=last.next; }else {return null; } } while (last.next!=null){ last=last.next; pre=pre.next; //同步移動 } return pre; } }
-----------------------------------------------------------------------------------------------------
參考鏈接:https://www.nowcoder.com/questionTerminal/529d3ae5a407492994ad2a246518148a
劍指offer十四之鏈表中倒數第k個結點