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

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

  • Total Accepted: 163106
  • Total Submissions: 417745
  • Difficulty: Easy
  • Contributors: Admin

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.

来源: 

分析


使用双指针, pre 和 cur,非递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 
* 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) {
        
if
(head == NULL || head->next == NULL) 
return 
head;
         
        
ListNode* pre = head;
        
ListNode* cur = head->next;
        
while
(cur != NULL){
            
if
(cur->val == pre->val){
                
ListNode * tmp = cur;
                
cur = cur->next;
                
pre->next = cur;
                
delete 
tmp;
            
}
            
else
{
                
pre = pre->next;
                
cur = cur->next;
            
}
        
}
        
return 
head;
    
}
};
递归法
删除head之后的list中重复元素,
然后再比较,如果head->val == head->next->val
则返回head->next
1
2
3
4
5
6
7
8
9
10
11
12
13
class 
Solution {
public
:
    
ListNode* deleteDuplicates(ListNode* head) {
         
if
(head == NULL || head->next == NULL) 
return 
head;
         
head->next = deleteDuplicates(head->next);
         
if
(head->next->val == head->val){
            
ListNode* tmp = head;
            
head = head->next;
            
delete 
tmp;
         
}
         
return 
head;
    
}
};

转载于:https://www.cnblogs.com/zhxshseu/p/e717dc1f6ac78e9258dd9a762acea20c.html

你可能感兴趣的文章
Masonry整理
查看>>
世界之大,无不分层
查看>>
linux redhat5+11g
查看>>
centOS7 安装 JAVA环境
查看>>
测试博文
查看>>
Miller-Rabin随机性素数测试算法(Miller_Rabin模板)
查看>>
转eclipse failed to create the java virtual machine
查看>>
研究float的一些好文章
查看>>
我的友情链接
查看>>
TCP/IP(二) —— TCP 概述
查看>>
ROS-Indigo版在Ubuntu上的安装
查看>>
Spark for Spatial,相关资源
查看>>
oracle数据导入导出
查看>>
Flask-RESTful构建小型REST服务
查看>>
LB集群--LVS部署
查看>>
AIX磁带备份
查看>>
ELK 6.4 实时日志分析系统
查看>>
Zend Studio使用教程之在Linux上进行安装
查看>>
linux下上传本地文件至github
查看>>
Android VelocityTracker
查看>>