题目如下:
这里提供两种思路,大同小异
- 思路一:统计链表长度,记录链表尾,根据总长和倒数N的位置计算删除节点之前的位置,删除返回
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// 链表总长
int len=0;
// 链表尾巴
ListNode tail=null;
ListNode tem=head;
while (tem!=null){
len++;
if(tem.next==null)
// 记录尾巴
tail=tem;
tem=tem.next;
}
if((len==1)&&n==1) return null;
// 这里是要删除节点的前置节点位置
int end=len-n;
int index=1;
ListNode te=head;
if(end<index)
return head.next;
while (te!=null){
if(index==end){
// 找到删除
ListNode next = te.next.next;
te.next=next;
break;
}
index++;
te=te.next;
}
return head;
}
}
- 思路二:使用快慢指针寻找待删除节点的前置节点。先让快指针走N步,然后快慢指针一起走到结尾,则慢指针的位置就是前置节点。
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head!=null&&head.next==null&&n==1) return head.next;
ListNode fast=head;
ListNode slow=head;
int fi=1;
// 先走N步
while (fi<=n){
fast=fast.next;
fi++;
}
if(fast==null)
return head.next;
while (true){
fast=fast.next;
if(fast==null)break;
slow=slow.next;
}
// 找到前置,删除
ListNode tem=slow.next.next;
slow.next=tem;
return head;
}
}