• LeetCode(82)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.

    分析

    该题目与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测试程序源码

  • 相关阅读:
    素数
    超级素数
    SUMMARIZE 6.1
    广度优先搜索与八字码问题
    poj2352
    poj1198
    康托展开
    STL里的内存池实现
    构造函数,C++内存管理,内存泄漏定位
    内联函数,宏定义,内存对齐,类型转换
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214840.html
Copyright © 2020-2023  润新知