20220923 - 83. Remove Duplicates from Sorted List 删除排序链表中的重复元素

117 阅读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]

  Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* deleteDuplicates(struct ListNode* head){
    if (head == NULLreturn head;
    struct ListNode *p = head, *q;
    while (p->next != NULL) {
        if (p->next->val == p->val) {
            q = p->next;
            p->next = q->next;
            free(q);
        } else {
            p = p->next;
        }
    }
    return head;
}

这里不用加头节点,像 20220923 - 203. Remove Linked List Elements 移除链表元素 一样操作判断删除重复元素即可。

题目链接: 83. 删除排序链表中的重复元素 - 力扣(LeetCode)