/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode preA = head;
ListNode preB = head;
for (int i = 0; i < k; i++) {
preB=preB.next;
}
//如果链表中节点个数小于等于k
if (preB==null) {
return head;
}
while (preB!=null) {
preA=preA.next;
preB=preB.next;
}
return preA;
}
}
剑指offer 22、链表中倒数第k个节点(简单)
最新推荐文章于 2022-05-22 16:45:04 发布