前言
删除链表的倒数第N个节点,涉及倒数基本需要快慢指针。
实现原理
删除链表的倒数第N个节点可以通过使用双指针技巧来实现。具体步骤如下:
- 使用两个指针,让它们之间相隔 N 个节点。
- 遍历链表,直到第一个指针到达链表末尾。
- 此时第二个指针指向的节点即为倒数第 N 个节点的前一个节点。
- 修改指针,将倒数第 N 个节点从链表中删除。
具体代码实现
package test3;
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// 让第一个指针先向前移动 n+1 步
for (int i = 0; i <= n; i++) {
first = first.next;
}
// 移动两个指针直到第一个指针到达末尾
while (first != null) {
first = first.next;
second = second.next;
}
// 删除第二个指针后面的节点
second.next = second.next.next;
return dummy.next;
}
public void printList(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.print(current.val + " -> ");
current = current.next;
}
System.out.println("null");
}
public static void main(String[] args) {
Solution solution=new Solution();
ListNode headA=new ListNode(0);
ListNode currentA=headA;
for(int i=5;i>=0;i--){
currentA.next=new ListNode(i);
currentA=currentA.next;
}
ListNode res=solution.removeNthFromEnd(headA.next,2);
solution.printList(res);
}
}
QA:待定