Open songyy5517 opened 1 month ago
Approach: Two Pointers (Fast & Slow)
Complexity Analysis
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteMiddle(ListNode head) {
// 思路:双指针(快慢指针)
// 1. 异常处理
if (head == null || head.next == null)
return null;
// 2. 定义双指针
ListNode slow = head, fast = head.next, pre = null;
// 3. 定位到中间节点
while (fast != null){
pre = slow;
slow = slow.next;
fast = fast.next == null ? null : fast.next.next;
}
// 4. 产出节点
pre.next = slow.next;
return head;
}
}
2024/5/26
You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list. The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.
Example 1:
Example 2:
Example 3:
Intuition This problem is basically to find the middle element in a linkedlist. A strightforward idea is to use two pointers, specifically fast & slow pointers, to loop through the entire linked list, where the fast pointer moves two step while the slow pointer moves just one step every iteration. Thereofre, when the fast pointer reaches the end of the linked list, the slow pointer will point to the middle element. In order to delete the middle element, we also need to define a pointer to the preceding element of the slow pointer.