C++ and Dart Solutions for Deleting the Middle Node of a Linked List
C++ and Dart Solutions for Deleting the Middle Node of a Linked List
This article presents C++ and Dart implementations for deleting the middle node of a linked list. The solutions leverage a fast and slow pointer technique to efficiently locate and remove the target node.
C++ Implementation
class Solution {
public:
ListNode* deleteMiddle(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return nullptr; // 头节点为空或只有一个节点时返回空指针
}
ListNode* p = head;
ListNode* q = head;
ListNode* prev = nullptr;
while (q != nullptr && q->next != nullptr) {
prev = p;
p = p->next;
q = q->next->next;
}
if (prev != nullptr) {
prev->next = p->next;
} else {
head = head->next; // 头节点为要删除的节点时更新头节点
}
delete p;
return head;
}
};
Dart Implementation
class Solution {
ListNode deleteMiddle(ListNode head) {
if (head == null || head.next == null) {
return null; // 头节点为空或只有一个节点时返回空指针
}
ListNode p = head;
ListNode q = head;
ListNode prev = null;
while (q != null && q.next != null) {
prev = p;
p = p.next;
q = q.next.next;
}
if (prev != null) {
prev.next = p.next;
} else {
head = head.next; // 头节点为要删除的节点时更新头节点
}
p = null;
return head;
}
}
Explanation
- Initialization: The code starts by initializing three pointers:
p,q, andprev.pis the slow pointer,qis the fast pointer, andprevpoints to the node beforep. - Fast and Slow Pointers: The
whileloop movesqtwo steps at a time, whilepmoves one step at a time. This ensures that whenqreaches the end of the list,pwill be pointing to the middle node. - Deletion: After the loop completes,
pwill be pointing to the middle node. The code then checks ifprevis not null (meaning the middle node is not the head). If so, it updatesprev'snextpointer to skip overp, effectively deleting it. Ifprevis null, the head node is the middle node, and we update theheadpointer to its next node. - Cleanup: Finally,
pis set tonullto break any potential circular references. The function returns the updatedheadpointer.
Conclusion
This article presented C++ and Dart implementations for deleting the middle node of a linked list. The solutions demonstrate the effectiveness of the fast and slow pointer technique in efficiently navigating and manipulating linked lists. By understanding these implementations, you can effectively delete middle nodes from linked lists in your own code.
原文地址: https://www.cveoy.top/t/topic/qhMu 著作权归作者所有。请勿转载和采集!