1.题目
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Example 1:
Input: head = [1,1,2] Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3] Output: [1,2,3]
2.思路
由题目可知,该链表已经是sorted的,只需要遍历链表,对重复的进行删除即可
3.代码
#include <iostream>
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* deleteDuplicates(ListNode* head) {
if (!head || !head->next) {
return head;
}
ListNode* current = head;
while (current->next) {
if (current->val == current->next->val) {
ListNode* temp = current->next;
current->next = temp->next;
delete temp; //删除释放内存
}
else {
current = current->next;
}
}
return head;
}
int main() {
// Create a sorted linked list: 1 -> 1 -> 2 -> 3 -> 3
ListNode* head = new ListNode(1);
head->next = new ListNode(1);
head->next->next = new ListNode(2);
head->next->next->next = new ListNode(3);
head->next->next->next->next = new ListNode(3);
std::cout << "Original Linked List: ";
ListNode* current = head;
while (current) {
std::cout << current->val << " ";
current = current->next;
}
std::cout << std::endl;
head = deleteDuplicates(head);
std::cout << "Linked List after removing duplicates: ";
current = head;
while (current) {
std::cout << current->val << " ";
current = current->next;
}
std::cout << std::endl;
// Clean up memory
current = head;
while (current) {
ListNode* temp = current;
current = current->next;
delete temp;
}
return 0;
}
4.总结
在删除节点时,我们需要跳过那些节点,但是我们还需要释放这些节点的内存,防止内存泄露,所以使用了 ListNode* tmp = cur->next 这一行代码