from typing import List
class ListNode():
def __init__(self, val):
self.val = val
self.next = None
def __str__(self):
return str(self.val)
def createList(value_list: list) -> ListNode:
"""
Create Linked List based on list
:param value_list: list
:return: NodeList
"""
_len = len(value_list)
if _len == 0:
return None
if _len == 1:
return ListNode(value_list[0])
else:
root = ListNode(value_list[0])
tmp = root
for i in range(1, _len):
tmp.next = ListNode(value_list[i])
tmp = tmp.next
return root
def printList(head: ListNode):
"""
Print single node one by one in linked list
:param head: ListNode
:return: None
"""
p = head
while p != None:
print(p)
p = p.next
def listLength(head: ListNode) -> int:
"""
Get the length of linked list
:param head: ListNode
:return: int
"""
count = 0
p = head
while p != None:
count += 1
p = p.next
return count
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head: return None
if head and not head.next: return head
is_pure = True
dummy = ListNode(None)
dummy.next = head
p = head
last = None
pre_p = dummy
while p and p.next:
if p.val == p.next.val:
p.next = p.next.next
last = p.val
elif p.val == last:
pre_p.next = p.next
p = p.next
is_pure = False
else:
pre_p = p
p = p.next
is_pure = False
if last == p.val:
pre_p.next = p.next
return None if is_pure else dummy.next
Input = [[1, 2, 3, 4, 4, 5, 5], [1,2,2], [1,2], [1], [2, 2, 2], [1,1], [1, 1, 2, 2, 3, 4, 5], [1, 2, 3, 3, 4, 4, 5], [1, 1, 1, 2, 3]]
Answer = [[1, 2, 3], [1], [1,2], [1], [], [], [3, 4, 5], [1, 2, 5], [2, 3]]
if __name__ == "__main__":
solution = Solution()
for i in range(len(Input)):
print("-"*50)
input_head = createList(Input[i])
reslut = solution.deleteDuplicates(input_head)
print(printList(reslut))
print(Answer[i])