題目描述
輸入一個鏈表,輸出該鏈表中倒數第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);
}
}