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.

解题思路:
简单的链表处理题,注意好指针处理就可以了
在处理中,出于细心考虑,把不要的节点delete掉,避免内存泄露

/**
 * 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 == 0)
            return head;
        int preVal = head -> val;
        ListNode *preNode = head;
        ListNode *tmp = head -> next;
        while(tmp){
            if(tmp -> val != preVal){
                preVal = tmp -> val;
                preNode -> next = tmp;
                preNode = preNode -> next;
                tmp = tmp -> next;
            }
            else{
                ListNode *preTmp = tmp;
                tmp = tmp -> next;
                delete preTmp;
            }
        }
        preNode -> next = 0;
        return head;
    }
};

leetcode的题解中提供一种只需要一个指针,不需要其他辅助指针的思路,也是挺不错的,可以参考下。

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