博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode:Remove Duplicates from Sorted List I II
阅读量:5872 次
发布时间:2019-06-19

本文共 2625 字,大约阅读时间需要 8 分钟。

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) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        if(head == NULL || head->next == NULL)return head;        ListNode *index = head, *p = head->next, *pre = head;        while(p != NULL)        {            if(p->val != pre->val)            {                index = index->next;                index->val = p->val;            }            pre = p;            p = p->next;        }        p = index->next;        index->next = NULL;        while(p != NULL)        {
//销毁多余的节点 ListNode *tmp = p; p = p->next; delete tmp; } return head; }};

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.                                                 

/** * 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) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        if(head == NULL)return head;        //为操作方便添加头结点        ListNode *addHead = new ListNode(0);        addHead->next = head;        //index 指向已经保存的最后一个节点        ListNode *index = addHead, *p = head;        while(p != NULL)        {            if(p->next == NULL || p->val != p->next->val)            {
//当前节点没有重复 index = index->next; index->val = p->val; p = p->next; } else {
//当前节点有重复,找到当前节点的最后一个副本的下一个元素 while(p->next && p->val == p->next->val) p = p->next; p = p->next; } } p = index->next; index->next = NULL; while(p != NULL) {
//销毁多余的节点 ListNode *tmp = p; p = p->next; delete tmp; } head = addHead->next; delete addHead; return head; }};

 

【版权声明】转载请注明出处:

转载于:https://www.cnblogs.com/TenosDoIt/p/3461481.html

你可能感兴趣的文章
PHP高手之路
查看>>
PHP 图片上传类 缩略图
查看>>
使用Leaflet创建地图拓扑图
查看>>
我的友情链接
查看>>
自动化运维框架
查看>>
FTP服务器管理和配置
查看>>
开源,并不意味着免费、开源,不是道德绑架
查看>>
无线传输测试方法
查看>>
大话射手座!
查看>>
mysql基础教程
查看>>
beaglebone black的cape管理
查看>>
查看当前Linux系统的发行版本命令详解
查看>>
memadmin
查看>>
我的友情链接
查看>>
centos7 配置虚拟交换机(物理交换机truck端口设置)(使用brctl)
查看>>
有软件开发,就要有软件测试!
查看>>
fpm打包
查看>>
框架会使程序员变笨吗?
查看>>
让你的大脑安静下来
查看>>
全面质量管理
查看>>