问题:删除链表的倒数第 N 个结点
tip:附全部代码,复制可运行。需要代码文档,算法解析的私得
全部代码
/**
* 2 * @Author: LJJ
* 3 * @Date: 2023/7/13 9:17
* 4
*/
public class LinkedListUtil {
static class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
this.next = null;
}
}
public static ListNode removeNthFromEnd(ListNode head,int n){
ListNode dummy = new ListNode(0); //创造一个虚拟头头节点
dummy.next = head;
// 使用快慢指针定位倒数第N个节点的前一个节点
ListNode fast = dummy;
ListNode slow = dummy;
dummy.next = head;
//将快指针向前移动N+1步
for (int i =0;i<=n;i++){
fast = fast.next;
}
// 同时移动快慢指针,直到快指针到达链表尾部
while (fast!=null){
slow = slow.next;
fast = fast.next;
}
// 删除倒数第N个节点
slow.next = slow.next.next;
//返回倒数第n个节点
return dummy.next;
}
public static void main(String[] args) {
// 创建链表:1 -> 2 -> 3 -> 4 -> 5
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
// 调用 removeNthFromEnd 方法删除倒数第2个节点
int n = 2;
ListNode result = removeNthFromEnd(head, n);
// 输出链表
while (result != null) {
System.out.print(result.val + " -> ");
result = result.next;
}
System.out.println("null");
}
}