zoukankan      html  css  js  c++  java
  • Leetcode 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.

    单链表移除重复元素问题

    注意到节点的删除即可,可能的变形题是移除循环双向链表的重复元素

    #include <iostream>
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    struct ListNode{
        int val;
        ListNode *next;
        ListNode(int x): val(x), next(NULL){}
    };
    
    ListNode *deleteDuplicates(ListNode *head){
        if(head == NULL ||  head-> next == NULL) return head;
        ListNode *p = head->next,  *pre = head;
        while(p){
            if(pre->val == p->val){
                ListNode *tmp = p->next;
                pre->next = p->next;
                delete p;
                p = tmp;
            }else{
                pre = p;
                p = p->next;
            }
        }
        return head;
    }
    
    void printList(ListNode *head){
        while(head){
            cout<<"-->"<<head->val;
            head = head->next;
        }
        cout<<endl;
    }
    
    int main(){
        ListNode *head = new ListNode(1);
       ListNode *p = new ListNode(2);
       head->next = p;
        printList(deleteDuplicates(head));
    }
  • 相关阅读:
    继承与多态,Instanceof关键字
    面向对象,单例模式
    方法
    数组
    流程控制
    基础语法
    连接linux四大远程工具
    MYSQL-索引的设计
    银行一类(Ⅰ类)、二类(Ⅱ类)、三类(Ⅲ类)账户区别是什么?
    真正有效的学习
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3801139.html
Copyright © 2011-2022 走看看