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.
分析
无
代码
- Java
- C++
- Python
// Remove Duplicates from Sorted List
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode p = head;
while (p != null && p.next != null) {
if (p.next.val == p.val) {
p.next = p.next.next;
} else {
p = p.next;
}
}
return head;
}
};
// Remove Duplicates from Sorted List
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
ListNode *p = head;
while(p && p->next) {
if (p->next->val == p->val) {
ListNode *tmp = p->next;
p->next = p->next->next;
delete tmp;
} else {
p = p->next;
}
}
return head;
}
};
# Remove Duplicates from Sorted List
# 时间复杂度O(n),空间复杂度O(1)
class Solution:
def deleteDuplicates(self, head):
p = head
while p and p.next:
if p.next.val == p.val:
tmp = p.next
p.next = p.next.next
del tmp
else:
p = p.next
return head