83. Remove Duplicates from Sorted List

題目原文

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

解題思路

  1. 前後兩兩相比較,如果是一樣的值,將head->next指向下一個數字的下一個。

  2. 如果兩兩不相等再將head指向下一個位置。

程式解答

class Solution 
{
public:
    ListNode* deleteDuplicates(ListNode* head) 
    {
        ListNode *p = (ListNode *)malloc(sizeof(struct ListNode));
        
        p->next = head;
        
        while (head && head->next)
        {
            if (head->val == head->next->val)
                head->next = head->next->next;
            else
                head = head->next;
        }
        return p->next;
    }
};

Last updated

Was this helpful?