#112 Remove Duplicates from Sorted List

来源:互联网 发布:健康风险评估软件 编辑:程序博客网 时间:2024/05/01 16:35

题目描述:

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.

题目思路:

这题比#113简单,因为不需要记录dup,只要判断node->val == node->next->val即可,如果为true,就绕过下一个node。

Mycode(AC = 41ms):

/** * Definition of ListNode * class ListNode { * public: *     int val; *     ListNode *next; *     ListNode(int val) { *         this->val = val; *         this->next = NULL; *     } * } */class Solution {public:    /**     * @param head: The first node of linked list.     * @return: head node     */    ListNode *deleteDuplicates(ListNode *head) {        // write your code here        ListNode *dummy = new ListNode(INT_MAX);        dummy->next = head;                ListNode *tmp = dummy;        while (tmp && tmp->next) {            if (tmp->val == tmp->next->val) {                tmp->next = tmp->next->next;                continue;            }                        tmp = tmp->next;        }                return dummy->next;    }};


0 0
原创粉丝点击