Niuke.com High-Frequency Algorithm Question Series-BM9-Delete the nth last node of the linked list
Topic description
Given a linked list, delete the nth last node of the linked list and return the head pointer of the linked list
See the original title: BM9 deletes the nth node from the bottom of the linked list
Solution 1: Double pointer method
First, consider two special cases:
- If the original linked list is empty, return null directly.
- If k is not a positive number, return null directly.
Otherwise, use two pointers to solve, the solving process is as follows:
- Because it is possible to delete the head node, first set a fake head node dummyNode and point to the original head node;
- Then, traverse the linked list and point the fast node to the n-1th node;
- If fast is null or the next of fast is empty after traversing, it means that the length of the linked list is less than n, there is no nth node from the bottom, and null is returned directly;
- Otherwise, the fast and slow pointers move together until fast moves to the penultimate node. At this time, slow is the penultimate n+1 node;
- Then remove the next node of slow, the nth node from the bottom;
- Finally, returning dummyNode.next is the new linked list after deleting the nth node.
code
public class Bm009 {
/**
* 双指针法
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public static ListNode removeNthFromEnd(ListNode head, int n) {
// 如果原链表为空,直接返回null
if (head == null) {
return null;
}
// 如果n不是正数,直接返回null
if (n <= 0) {
return null;
}
// 因为有可能删掉头结点,所以先设置一个假的头结点,并指向原有的头结点
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode fast = dummyNode;
// 将fast结点指向第n-1个结点
for (int i = 0; i < n - 1 && fast != null; i++) {
fast = fast.next;
}
// 如果fast为null或者fast的next结点为空,说明链表长度小于n,不存在倒数第n个结点,直接返回null
if (fast == null || fast.next == null) {
return null;
}
ListNode slow = dummyNode;
// 快慢指针一起移动,直到fast移动到最后第二个结点,此时,slow即为倒数第n+1个结点
while (fast.next.next != null) {
slow = slow.next;
fast = fast.next;
}
// 将slow的next结点即倒数第n个结点移除
slow.next = slow.next.next;
return dummyNode.next;
}
public static void main(String[] args) {
ListNode pHead = ListNode.testCase2();
System.out.println("原链表为");
ListNode.print(pHead);
int k = 2;
System.out.println("删除链表中的倒数第" + k + "个结点后:");
ListNode.print(removeNthFromEnd(pHead, k));
}
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。