83. 删除排序链表中的重复元素

https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/description/

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

输入: 1->1->2
输出: 1->2

示例 2:

输入: 1->1->2->3->3
输出: 1->2->3
/**
 * 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 == NULL){
            return head;
        }
        ListNode* cur = head;
        ListNode* next = cur->next;
        ListNode* temp = NULL;
        while(cur->next){
            next = cur->next;
            if(cur->val == next->val){
                temp = next;
                cur->next = next->next;
                delete temp;
            }
            else{
                cur = cur->next;
            }
        }
        return head;
    }
};

83. 删除排序链表中的重复元素

看了下运行时间最快的算法,分析了一下,LeetCode编程都不注意内存回收的嘛,以空间换时间(好像不是一般我们说的空间换时间算法哈。。。),内存泄漏。。。。

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