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
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
思路: 记录节点信息,有重复的跳过,没有重复的加到一个新的链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
newhead = ListNode(0)
result = newhead
if head == None:
return None
node = head.next
ref = head.val
flag = False
while node != None:
if node.val == ref:
flag = True
node = node.next
else:
if flag == False:
newhead.next = ListNode(ref)
newhead = newhead.next
flag = False
ref = node.val
node = node.next
if flag == False:
newhead.next = ListNode(ref)
newhead.next.next = None
return result.next