Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example:
- Given
1->2->3->3->4->4->5
, return1->2->5
. - Given
1->1->1->2->3
, return2->3
.
C Solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode dummy, *p = &dummy;
p->next = head;
struct ListNode *l = head, *r;
while (l) {
r = l->next;
while (r && r->val == l->val) r = r->next;
if (r != l->next) p->next = r;
else p = l;
l = r;
}
return dummy.next;
}
Python Solution 1:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next: return head
dummy = ListNode(0)
dummy.next = head
cur, r, rr = dummy, head, head.next
while r and rr:
if r.val != rr.val:
cur, r, rr = r, rr, rr.next
continue
val = r.val
while cur.next:
if cur.next.val != val: break
cur.next = cur.next.next
if not cur.next: break
r, rr = cur.next, cur.next.next
return dummy.next
Python Solution 2:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next: return head
dummy = ListNode(0)
dummy.next = head
cur, r = dummy, head
while r:
rr = r.next
while rr and rr.val == r.val:
rr = rr.next
if rr != r.next:
cur.next = r = rr
else:
cur, r = r, rr
return dummy.next
Summary:
- 3ms, 21.13%
- Whether I should free the deleted node is not sure, it's necessary to discuss with the interviewer.
近期评论