目录
- 1- 思路
-
- 2- 实现
- ⭐19. 删除链表的倒数第 N 个结点——题解思路
- 3- ACM 实现
1- 思路
双指针
- 定义
dummyHead
处理头结点情况 slow
指针:初始化为 dummyHead
定位到被移除元素的前一个fast
指针:初始化诶 dummyHead
,从 dummyHead
开始 先移动 n
位- 之后 同时移动
slow
和 fast
,终止条件是 while(fast.next!=null)
2- 实现
⭐19. 删除链表的倒数第 N 个结点——题解思路
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode slow = dummyHead;
ListNode fast = dummyHead;
for(int i = 0 ; i < n;i++){
fast = fast.next;
}
while(fast.next!=null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummyHead.next;
}
}
3- ACM 实现
public class removeN {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode slow = dummyHead;
ListNode fast = dummyHead;
for(int i = 0 ; i < n;i++){
fast = fast.next;
}
while(fast.next!=null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummyHead.next;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
ListNode head1 = null, tail1 = null;
for (int i = 0; i < n1; i++) {
int val = sc.nextInt();
ListNode newNode = new ListNode(val);
if (head1 == null) {
head1 = newNode;
tail1 = newNode;
} else {
tail1.next = newNode;
tail1 = newNode;
}
}
System.out.println("输入n");
int nth = sc.nextInt();
ListNode forRes = removeNthFromEnd(head1,nth);
while(forRes!=null){
System.out.print(forRes.val+"");
forRes = forRes.next;
}
}
}