[点击进入 牛客网题库:链表中倒数第k个结点]
题目描述
输入一个链表,输出该链表中倒数第k个结点。
这个题目就是通过一个快指针和慢指针来进行的
public class Solution {
public ListNode FindKthToTail(ListNode head, int k) {
if(head == null || k <= 0) {
return null;
}
ListNode fast = head;
ListNode slow = head;
for(int i = 0; i < k; i++) {
if(fast == null) {
return null;
}
fast = fast.next;
}
while(fast != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
public class Solution {
public ListNode FindKthToTail(ListNode head, int k) {
if(head == null || k <= 0) {
return null;
}
ListNode fast = head;
ListNode slow = head;
while(fast!=null) {
fast = fast.next;
k--;
if(k < 0) {
slow = slow.next;
}
}
if(k > 0) {
return null;
}
return slow;
}
}
网友评论