小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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.

分析

该题目与LeetCode 83题目类似,都是删除链表中重复元素的题目。
该题目要求只保存不重复的结点!

详细见代码!

AC代码

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (head == NULL || head->next == NULL)
            return head;

        ListNode * p = head;

        while (p->next != NULL && p->val == p->next->val)
        {
            p = p->next;
        }

        //保存结点
        ListNode *r = p->next;

        //如果头结点是重复的
        if (p != head){
            while (head != r)
            {
                ListNode * tmp = head;
                head = head->next;
                free(tmp);
            }
            return deleteDuplicates(head);
        }

        //否则递归处理接下来的结点
        head->next = deleteDuplicates(head->next);
        return head;
    }
};

GitHub测试程序源码

posted on 2015-09-22 21:33  Coding菌  阅读(125)  评论(0编辑  收藏  举报