83. Remove Duplicates from Sorted List

题目描述:给一个排好序的链表,删除其中的重复元素。如:

Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3

分析:简单的快慢指针应用,时间复杂度O(n),空间O(1)。

代码

/**
 * 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) return head;
        ListNode *pre = head, *cur;
        for (cur = head -> next; cur; cur = cur -> next)
        {
            if (pre -> val == cur -> val)
            {
                pre -> next = cur -> next;
                delete cur;
            }
            else
                pre = cur;
        }
        return head;
    }
};

你可能感兴趣的:(83. Remove Duplicates from Sorted List)