跳到主要内容

Remove Duplicates from Sorted List

描述

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.

分析

解法1: 递归版

// Remove Duplicates from Sorted List
// 递归版,时间复杂度O(n),空间复杂度O(n)
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;

ListNode newHead = deleteDuplicates(head.next);
if(head.val == newHead.val) {
return newHead;
} else {
head.next=newHead;
}
return head;
}
};

解法2: 迭代版

// Remove Duplicates from Sorted List
// 迭代版,时间复杂度O(n),空间复杂度O(1)
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return null;

for (ListNode slow = head, fast = head.next; fast != null; fast = slow.next) {
if (slow.val == fast.val) {
slow.next = fast.next;
} else {
slow = fast;
}
}
return head;
}
};

相关题目