[LeetCode] 83. Remove Duplicates from Sorted List

题目:

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

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

简单题。第一次通过的时候没有加入对head是null的判断,运行23ms,加入了以后只有12ms。必要的判断加入还是能提高很多效率的。

/**
 * 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* cur = head;
        
        while(cur){
            if (!cur->next) break;
            if (cur->next->val == cur->val){
                cur->next = cur->next->next;
            }
            else{
                cur = cur->next;
            }
        }
        
        return head;
    }
};

 

posted on 2016-09-04 10:19  医生工程师  阅读(144)  评论(0编辑  收藏  举报

导航