LeetCode 83 存在一个按升序排列的链表,请你删除所有重复的元素,使每个元素只出现一次。
LeetCode 83:
题目要求删除链表中重复的元素,使每个元素只出现一次。
解题思路:
由于链表已经按升序排列,我们可以使用双指针来解决这个问题。
1. 初始化两个指针,一个指向当前节点cur,一个指向下一个节点next。
2. 当cur的值与next的值相同时,说明存在重复元素,此时我们将cur的next指针指向next的下一个节点,跳过重复节点。
3. 如果cur的值与next的值不同,则将cur指向next,继续遍历下一个节点。
4. 重复上述步骤,直到cur指向NULL,即链表的末尾。
代码片段:
struct ListNode* deleteDuplicates(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode* cur = head;
while (cur->next != NULL) {
struct ListNode* next = cur->next;
if (cur->val == next->val) {
cur->next = next->next;
free(next);
} else {
cur = next;
}
}
return head;
}
LeetCode 82 存在一个按升序排列的链表,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中没有重复出现的数字。
LeetCode 82:
题目要求删除链表中存在数字重复情况的节点,只保留原始链表中没有重复出现的数字。
解题思路:
与LeetCode 83类似,我们同样可以使用双指针解决这个问题。
1. 初始化两个指针,一个指向当前节点cur,一个指向下一个节点next。
2. 当cur的值与next的值相同时,说明存在重复元素,此时我们需要找到这个重复元素的最后一个节点。
3. 使用一个while循环,找到最后一个重复节点,即当next的值与cur的值相同时,不断将next移动到下一个节点,直到next的值与cur的值不同为止。
4. 在这个过程中,我们将遍历到的重复节点都释放掉。
5. 最后,将cur的next指针指向最后一个重复节点的下一个节点,跳过了所有重复节点。
6. 重复上述步骤,直到cur指向NULL,即链表的末尾。
代码片段:
struct ListNode* deleteDuplicates(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode dummy;
dummy.next = head;
struct ListNode* cur = &dummy;
while (cur->next != NULL && cur->next->next != NULL) {
if (cur->next->val == cur->next->next->val) {
int duplicateVal = cur->next->val;
while (cur->next != NULL && cur->next->val == duplicateVal) {
struct ListNode* temp = cur->next;
cur->next = cur->next->next;
free(temp);
}
} else {
cur = cur->next;
}
}
return dummy.next;
}