• 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;
        }
    };
  • 相关阅读:
    C语言常用函数
    信号处理函数误用不可重入函数导致的进程死锁情况
    Shell脚本学习
    文件I/O详解
    字体标记的使用
    无序列表标记
    换行标记的使用
    HTML文件的基本结构
    预格式化标记的使用
    特殊标记的使用
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4481267.html
Copyright © 2020-2023  润新知