删除链表的倒数第n个结点

问题陈述

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

1
2
3
给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

思路分析

定义一个pre结点,pre.next=head。然后定义两个指针first,second。first先走n步,然后一起走,当first为空跳出,此时second指向了被删结点的前一个结点,执行删除。最后返回pre.next。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution{
public ListNode removeNthFromEnd(ListNode head,int n){
ListNode pre=new ListNode(0);
pre.next=head;
ListNode first=pre,second=pre;
while(n!=0){
first=first.next;
n--;
}
while(first.next!=null){
first=first.next;
second=second.next;
}
second.next=second.next.next;
return pre.next;
}
}