leetCode #82 Remove Duplicates from Sorted List

題目:從一個有序鏈表裏刪除重複元素

分析:這個和數組去重很像。都只需記錄下當前不重複的元素位置到下一個不重複的元素位置,然後建立聯繫即可。

答案:

/**
 * 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) {
        ListNode* pre = head;
        
        if (head == NULL)
            return head;
        ListNode* nextp = head->next;
        
        while(nextp){
            if (nextp->val == pre->val){
                nextp = nextp->next;
                pre->next = NULL; // 臨時先指向null
            }
            else{
                pre->next = nextp; 
                pre = pre->next;
                nextp = nextp->next;
            }
        }
        return head;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章