zoukankan      html  css  js  c++  java
  • Remove Duplicates from Sorted List I & II

    Title:

    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.

    /**
     * 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) {
            ListNode* p = head;
            ListNode* pre = NULL;
            while (p != NULL){
                if (pre != NULL && p->val == pre->val){
                        pre->next = p->next;
                        delete p;
                        p = pre->next;
                }
                else{
                        pre = p;
                        p = p->next;
                }
            }
            return head;
        }
    };

    Title:

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.

    class Solution{
        public:
    ListNode *deleteDuplicates(ListNode *head) {
            if(head == NULL || head->next == NULL){
                return head;
            }
            ListNode *p = new ListNode(-1);
            p->next = head;
            ListNode *cur = p, *pre = head;
            while(pre != NULL){
                bool isDupli = false;
                while(pre->next != NULL && pre->val == pre->next->val){
                    isDupli = true;
                    pre = pre->next;
                }
                if(isDupli){
                    pre = pre->next;
                    continue;
                 
                }
                cur->next = pre;
                cur = cur->next;
                pre = pre->next;
                
            }
            cur->next = pre;
            return p->next;
        }
    };
  • 相关阅读:
    Git工作原理
    将博客搬至CSDN
    Hive常见文件存储格式
    Hadoop进入安全模式源码分析
    Hadoop RPC简介
    hive自定义UDF函数
    hive性能调优之表设计层面调优
    flowable 启用慢 且启动不起来 报错看不懂
    数据结构和算法基础
    css: 边宽弧度
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4481267.html
Copyright © 2011-2022 走看看