题目
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
思路一
利用set不能存储相同元素特性,如果set添加成功就继续,否则就删除该结点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
//Step1:判断特殊情况
if(head == null || head.next == null) return head;
//Step2:定义辅助变量,利用集合不能存储相同的元素特点来判断该结点是否重复
HashSet<Integer> set = new HashSet<>();
ListNode p = head.next, q = head;
set.add(q.val);
while(p != null){
if(!set.add(p.val)){
q.next = p.next;
}else{
q = q.next;
}
p = p.next;
}
//Step3:输出结果
return head;
}
}
思路二
由于链表是有序的,可以比较相邻结点值,如果不相等则后移,否则删除相邻结点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
//Step1:判断特殊情况——空链表或者只有一个结点
if(head == null || head.next == null) return head;
//Step2:由于该链表是排序的,可以比较相邻结点,删除重复元素
ListNode pre = head, cur = head.next;
while(cur != null){
if(pre.val == cur.val){//一直比较相邻结点,直到不相等时才移到下一个结点
pre.next = cur.next;
}else{
pre = pre.next;
}
cur = cur.next;
}
//Step3:输出结果
return head;
}
}
思路三
递归法:
1.终止条件:当head为空或者只有一个结点时返回该结点;
2.如果当前结点和下个结点重复,则返回下个结点;
class Solution {
public ListNode deleteDuplicates(ListNode head) {
//Step1:判断特殊情况——空链表或者只有一个结点
if(head == null || head.next == null) return head;
//Step2:递归
head.next = deleteDuplicates(head.next);
if(head.val == head.next.val){
return head.next;
}
//Step3:输出结果
return head;
}
}