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的題解中提供一種只需要一個指針,不需要其他輔助指針的思路,也是挺不錯的,可以參考下。

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