找到单链表中倒数第k个结点。解题思路是双指针,第一个指针从头向尾部一定k-1位,然后这时候第二个指针再从头部开始移动,当第一个指针移动到尾部的时候,第二个指针指的位置就是倒数第K个。这里需要考虑一些特殊情况,比如头结点为空、k==0、k>链表中的结点数。还需要注意一点的就是倒数第k个,k是从1开始的。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null||n==0){
return null;
}
ListNode fast=head;
ListNode slow=null;
for(int i=0;i<n-1;i++){
if(fast.next!=null){
fast=fast.next;
}
else{
return null;
}
}
slow=head;
while(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
return slow;
}
}
上面只是找到了倒数第k各结点,但是如果要删除这个结点,
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy=new ListNode(0);
dummy.next = head;
if(head==null||n==0){
return null;
}
ListNode fast=dummy;
ListNode slow=dummy;
while(fast.next!=null){
if(n<=0){
slow=slow.next;
}
fast=fast.next;
n--;
}
if(slow.next!=null)
slow.next=slow.next.next;
return dummy.next;
}
}
类似的使用双指针的还有判断链表时候否有环,寻找链表的中间结点。