天天看點

LeetCode 83.Remove Duplicates from Sorted List (删除排序連結清單中的重複元素)

題目描述:

給定一個排序連結清單,删除所有重複的元素,使得每個元素隻出現一次。

示例 1:

輸入: 1->1->2
輸出: 1->2
      

示例 2:

輸入: 1->1->2->3->3
輸出: 1->2->3      

AC C++ Solution:

/**
 * 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 || !head->next) return head;
       
        ListNode *pre = head; 
        while(pre->next!=NULL)
        {
            if(pre->val == pre->next->val)
            {
                ListNode* temp = pre->next;
                pre->next = temp->next;
                delete temp;
            }else
                pre = pre->next;
            
        }
        return head;
    }
};