Given a sorted linked list, delete all duplicates such that each element appear only once.node
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.python
# 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 """ node = head while node: tmp = node val = node.val while node.next and node.next.val == val: node = node.next # assert node.next is None or node.next.val != val tmp.next = node.next node = node.next return head
# 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 """ dummy = cur = ListNode(None) node = head while node: if node.val != cur.val: cur.next = node cur = cur.next node = node.next cur.next = None return dummy.next
發現其餘人的解法和個人都不同,每次上一個節點比較,若是數值相同,則直接刪除當前節點。app
# 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: return None node = head while node.next: if node.next.val == node.val: node.next = node.next.next else: node = node.next return head
遞歸解法:code
# 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: return None if not head.next: return head head.next = self.deleteDuplicates(head.next) if head.val == head.next.val: return head.next else: return head