Remove Duplicates From Sorted List

题目:

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

Example

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

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

分析:

这道题目不需要dummy node因为head总是会被保留下来。如果是II的话,就未必如此。

解法:

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */
    ListNode *deleteDuplicates(ListNode *head) {

        if (head == NULL) {
            return NULL;
        }

        ListNode* curr = head;
        while (curr->next != NULL) {
            if (curr->val == curr->next->val) {
                curr->next = curr->next->next;
            } else {
                curr = curr->next;
            }
        }

        return head;
    }
};

results matching ""

    No results matching ""