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
.
# 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
发现其他人的解法和我的都不一样,每次上一个节点比较,如果数值相同,则直接删除当前节点。
# 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
递归解法:
# 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
标签:node,head,ListNode,val,Duplicates,self,List,Remove,next From: https://blog.51cto.com/u_11908275/6381010