leetcode 83. Remove Duplicates from Sorted List

来源:互联网 发布:mac page up 编辑:程序博客网 时间:2024/06/14 23:56

题目描述:
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的题解中提供一种只需要一个指针,不需要其他辅助指针的思路,也是挺不错的,可以参考下。

0 0