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;
        }
    };
  • 相关阅读:
    Leetcode 242.有效的字母异位词 By Python
    Leetcode 344.反转字符串 By Python
    Leetcode 217.存在重复元素 By Python
    js 动态加载select触发事件
    MUI 里js动态添加数字输入框后,增加、减少按钮无效
    【 jquery 】常用
    MySql 常用语句
    CSS 选择器 知识点
    HTML 符号实体
    log4net 配置
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4481267.html
Copyright © 2011-2022 走看看