输入一个链表,输出该链表中倒数第k个结点。
package 剑指Offer.链表中倒数第k个结点;
public class Solution {
public ListNode FindKthToTail(ListNode head, int k) {
if (head == null || k <= 0) {
return null;
}
ListNode aListNode = head;
for (int i = 0; i < k - 1; i++) {
aListNode = aListNode.next;
}
if (aListNode == null) {
return null;
}
ListNode bListNode = head;
while (aListNode.next != null) {
aListNode = aListNode.next;
bListNode = bListNode.next;
}
return bListNode;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
网友评论