给定一个已排序的链表的头 head
, 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
示例:
输入:head = [1,1,2]
输出:[1,2]
方法一:递归
class Solution {
public ListNode deleteDuplicates(ListNode head) {
// 递归终止条件
if (head==null||head.next==null){
return head;
}
// 递归操作
if (head.val==head.next.val){
head=deleteDuplicates(head.next);
}else {
head.next=deleteDuplicates(head.next);
}
return head;
}
}
方法二:快慢指针
class Solution {
public ListNode deleteDuplicates(ListNode head) { // 递归终止条件
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
ListNode slow = cur;
ListNode fast = cur.next;
while (fast != null) {
while (slow.val == fast.val) {
slow.next = fast.next;
fast = fast.next;
if (fast == null) {
return head;
}
}
slow = slow.next;
fast = fast.next;
}
return head;
}
}