题目:
AC:
package 链表;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class 删除倒数第几个节点 {
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; }
}
public ListNode removeNthFromEnd(ListNode head, int n) {
//ListNode dummy= new ListNode(0,head);
ListNode first=head;
ListNode second=head;
for (int i = 0; i <n ; i++) {
first=first.next;
}
if(first==null){
head=head.next;
return head;
}
while (first.next!=null){
first=first.next;
second=second.next;
}
second.next=second.next.next;
return head;
}
public ListNode removeNthFromEnd2(ListNode head, int n) {
ListNode dummy= new ListNode(0,head);
ListNode first=head;
ListNode second=dummy;
for (int i = 0; i <n ; i++) {
first=first.next;
}
// if(first==null){
// head=head.next;
// return head;
// }
while (first!=null){
first=first.next;
second=second.next;
}
second.next=second.next.next;
return head;
}
public ListNode removeNthFromEnd3(ListNode head, int n) {
ListNode dummy= new ListNode(0,head);
Deque<ListNode> stack=new LinkedList<>();
ListNode cur=dummy;
while (cur!=null){
stack.push(cur);
cur=cur.next;
}
for (int i = 0; i <n ; i++) {
stack.pop();
}
ListNode node=stack.peek();
node.next=node.next.next;
return dummy.next;
}
}
PS:
一共是3种做法
1 其中如果没有娅节点定义的话 快慢指针都在head节点开始,那么有个极端问题就是如果删除的是头节点 有一个判空问题
因为这里的first不能为空
2 定义娅节点 很好用 慢指针一开始在娅节点 不然如果一开始都在头节点 那么最后快节点到达null,慢节点到达要删除的,而用娅节点后,则刚刚好下一个就是要删除的
3 栈