Leetcode 19. 删除链表中倒数的第N个节点
本来想用回溯做的,结果发现了很多问题,需要添加很多特例才能成功跑完...
/**
* 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 removeNthFromEnd(ListNode head, int n) {
if(n<0){
return null;
}
int i = 0;
ListNode ans = head;
ListNode ans1 = head;
while(head!=null){
if(i-n>=1){
ans = ans.next;
}
if(head.next==null){
i++;
break;
}
head = head.next;
i++;
}
if(i==1){
return null;
}
if(i==2){
if(n==1){
return new ListNode(ans.val);
}
if(n==2){
return ans.next;
}
}
if(i==n){
return ans1.next;
}
ans.next = ans.next.next;
return ans1;
}
}
实际上用快慢指针更方便哒
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy=new ListNode(0, head);
ListNode slow=head,fast=head;
int i=0;
//快慢一块走,快的走n步时,让slow返回起点重新走(让slow到达删除节点的pre)
//以快指针为空,作为判断遍历结束的条件。
while (fast != null){
slow = slow.next;
fast = fast.next;
i++;
if (i == n) slow = dummy;
}
slow.next = slow.next.next;
return dummy.next;
}