题目描述:
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
Solution1:
将头结点与下一个节点值比较,若相等,则把下下个节点值赋给下个节点值;若不相等,则继续遍历链表
code:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates2(self,head):
'''
:param head:ListNode
:return: ListNode
'''
if head == None:
return head
cur = head
while cur.next:
if cur.val == cur.next.val:
cur.next.val = cur.next.next.val
else:
cur = cur.next
return head
Solution2:
使用dictionary字典记录链表中每个value的个数,用list存放去重的链表当中的value
code:
class Solution:
def deleteDuplicates(self,head):
'''
:param head: ListNode
:return: ListNode
'''
valuedict = {}
valuelist = []
head2 = ListNode(0)
p = head2
while head:
if head.val in valuedict:
valuedict[head.val] += 1
else:
valuelist.append(head.val)
valuedict[head.val] = 1
head = head.next
for i in valuelist:
if valuedict[i] == 1:
new = ListNode(i)
p.next = new
p = p.next
return head2.next