113. 删除排序链表中的重复数字 II
给定一个排序链表,删除所有重复的元素只留下原链表中没有重复的元素。
样例
给出 1->2->3->3->4->4->5->null
,返回 1->2->5->null
给出 1->1->1->2->3->null
,返回 2->3->null
实现思路:
定义两个指针,对链表进行遍历,如果两个指针相等,就删除所有等于该值的结点。
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: head is the head of the linked list
@return: head of the linked list
"""
def deleteDuplicates(self, head):
# write your code here
if head is None or head.next is None:
return head
tmp = dummy = ListNode(0)
tmp.next = head
pre = head
cur = head.next
while cur:
#如果两个节点相等,则tmp.next = None
if pre.val == cur.val:
tmp.next = None
flag = pre.val
#因为是一位一位的位移,所以判断pre的值
#如果pre的值等于flag,就忽略
while pre.val == flag:
pre = pre.next
#当进行到尾结点时cur为none,所以返回
if cur is None:
break
cur = cur.next
else:
tmp.next = pre
tmp = tmp.next
pre = pre.next
cur = cur.next
return dummy.next