83. Remove Duplicates from Sorted List

problem description

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

algorithm thought

和上一题一样,甚至比上一题简单,使用递归解决

code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head==NULL||head->next==NULL)
            return head;
        ListNode* next=head->next;
        while(next&&next->val==head->val){
            next=next->next;
        }
        head->next=deleteDuplicates(next);
        return head;
    }
};

algorithm analysis

一次遍历解决问题,时间复杂度O(n)

Last updated