找倒数第k个节点
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
int len=getlen(head);
if(k<0||k>len){
return null;
}
ListNode fast=head;
ListNode slow=head;
//为什么是k,停止的条件是fast=null,也就是说-1的位置
for(int i=0;i<k;i++){
fast=fast.next;
}
while(fast!=null){
fast=fast.next;
slow=slow.next;
}
return slow;
}
int getlen(ListNode p){
int i=0;
while(p!=null){
i++;
p=p.next;
}
return i;
}
}
删除倒数第k个节点
Given a linked list, remove the n-th node from
the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
- 其实很简单,双指针问题(找好fast比slow快多少步,fast先走n步,slow和fast同步走就好了,最后fast到最后一个节点就好了)
- 注意删除头结点的情况
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int len=getlen(head);
if(n<0||n>len){
return null;
}
if(n==len){
return head.next;
}
ListNode fast=head;
ListNode slow=head;
for(int i=0;i<n+1;i++){
fast=fast.next;
}
while(fast!=null){
fast=fast.next;
slow=slow.next;
}
slow.next=slow.next.next;
return head;
}
int getlen(ListNode p){
int i=0;
while(p!=null){
i++;
p=p.next;
}
return i;
}
}
_________________________分割线—————————————————
这个题还挺有意思,一边应用了快慢指针,但是跟基本的找出链表倒数第k个节点还不太一样
不一样的地方在这里:
1找到节点问题:删除倒数第k个节点其实实际上找到的是倒数k+1个节点,然后用如下代码删除 pslow->next
这个双指针问题要跟查找链表的中间节点的双指针区分清楚
这个是要删除的节点(也就是倒数第k个节点跟最后一个节点间隔k-1的距离)
另一种双指针是找中间节点的双指针,慢指针走一步,快指针走两步
pslow->next=pslow->next->next;