引言:
剑指 Offer 22. 链表中倒数第k个节点
![](https://i-blog.csdnimg.cn/blog_migrate/434bd498b45cd8265fc9d760c7c1e28a.png)
/**
* 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 p1 = head,p2=head;
int len=1;
for(int i=0;i<k;++i){
p1 = p1.next;
}
while(p1 != null){
p1=p1.next;
p2=p2.next;
}
return p2;
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/47dde1308dc8c11e97b40ea7a990f74a.png)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode findNthFromEnd(ListNode head, int n) {
ListNode p1 = head,p2=head;
int len=1;
for(int i=0;i<n;++i){
p1 = p1.next;
}
while(p1 != null){
p1=p1.next;
p2=p2.next;
}
return p2;
}
public ListNode removeNthFromEnd(ListNode head, int n) {
// 虚拟头结点,避免findNthFromEnd(n+1)的pre为空
ListNode dummy = new ListNode(-1);
dummy.next = head;
// 删除倒数第 n 个,要先找倒数第 n + 1 个节点
ListNode pre = findNthFromEnd(dummy,n+1);
pre.next = pre.next.next;
return dummy.next;
}
}
注意dummy的用法