给定一个已排序的链表的头 head
, 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
示例 1:
输入:head = [1,2,3,3,4,4,5] 输出:[1,2,5]
示例 2:
输入:head = [1,1,1,2,3] 输出:[2,3]
提示:
- 链表中节点数目在范围
[0, 300]
内-100 <= Node.val <= 100
- 题目数据保证链表已经按升序 排列
1.三指针法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
//判断是否为空
if(head == null || head.next == null){
return head;
}
//三指针
ListNode prev = new ListNode(-101);
prev.next = head;
ListNode fir = head;
ListNode x = prev;
while(fir.next != null){
ListNode sec = fir.next;
//先判断fir与sec是否相等
//如果不相等说明fir是不重复的
if(fir.val != sec.val){
x.next = fir;
x = x.next;
fir = fir.next;
sec = fir.next;
//如果相等,则fir到sec一个都不能留
//找到往后第一个与fir不相等的节点
}else{
while(sec != null && sec.val == fir.val){
sec = sec.next;
}
//判断是否为空
if(sec == null){
x.next = sec;
break;
}
//此时sec的值不相等,将fir到sec之间的值全部删掉
fir = sec;
sec = fir.next;
}
//出循环说明
}
if(fir.next == null){
x.next = fir;
}
return prev.next;
}
}
2.递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
//判断是否为空
if(head == null || head.next == null){
return head;
}
//判断头节点
//如果头节点重复,把与头节点重复的元素都删掉
//找到第一个与头节点不重复的元素
if(head.val != head.next.val){
head.next = deleteDuplicates(head.next);
return head;
}else{
//创建一个空节点,找到第一个与头节点不重复的元素
ListNode dummyHead = new ListNode();
dummyHead.next = head;
while(head.next != null && head.val == head.next.val){
head = head.next;
}
return deleteDuplicates(head.next);
}
}
}