要设计算法去除单链表中数值相同的元素,可以使用双指针法进行遍历和比较。
- 初始化两个指针:current 指向链表头节点,runner 指向 current 的下一个节点。
- 进行循环遍历:
- 如果 current 节点的值与 runner 节点的值相同,则将 runner 节点删除,并将 runner 后移一位;
- 如果 current 节点的值与 runner 节点的值不同,则将 current 和 runner 都后移一位。
- 重复步骤 2,直到 runner 遍历完整个链表。
- 返回处理后的链表。
该算法的时间复杂度为 O(n),其中 n 是链表中的元素个数。由于需要对每个节点进行遍历和比较,所以时间复杂度是线性的。
实现代码可能如下所示:
#include <iostream>
struct Node {
int data;
Node* next;
};
Node* removeDuplicates(Node* head) {
if (head == nullptr) return nullptr;
Node* current = head;
while (current != nullptr && current->next != nullptr) {
Node* runner = current;
while (runner->next != nullptr) {
if (runner->next->data == current->data) {
Node* temp = runner->next;
runner->next = runner->next->next;
delete temp; // 释放内存
} else {
runner = runner->next;
}
}
current = current->next;
}
return head;
}
void printList(Node* head) {
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << std::endl;
}
int main() {
Node* head = new Node{1, nullptr};
Node* second = new Node{2, nullptr};
Node* third = new Node{2, nullptr};
Node* fourth = new Node{3, nullptr};
head->next = second;
second->next = third;
third->next = fourth;
std::cout << "Original list: ";
printList(head);
removeDuplicates(head);
std::cout << "List after removing duplicates: ";
printList(head);
// 释放内存,防止内存泄漏
delete fourth;
delete third;
delete second;
delete head;
return 0;
}
注意,在实际使用中还需要考虑边界情况和正确地释放内存。
内容由零声教学AI助手提供,问题来源于学员提问