##題目描述 輸入一個鏈表,輸出該鏈表中倒數第k個結點,
思路
快慢指標注意邊界,
時間復雜度O(n),空間復雜度O(1),
代碼
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head == null || k < 1) return null;
ListNode slow = head;
ListNode fast = head;
for(int i = 1; i < k; i++){
if(fast.next == null) {
return null;
}
fast = fast.next;
}
while(fast.next != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/86927.html
標籤:其他
上一篇:調整陣列順序使奇數位于偶數前面
下一篇:反轉鏈表
