83 | Remove Duplicates from Sorted List | 40.20% | 删去listnode中的重复元素,a.next=a.next.next(单链表的删除) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 8 17:59:50 2018
@author: vicky
"""
#参见21题
#Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def display(self):
while self:
print(self.val)
self=self.next
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
a=head #listnode跟list一样都为可变变量,对a改变同时head也 有可能 改变
while a and a.next:
if a.val!=a.next.val:
#a.next=ListNode(a.next.val) 错误!!
#不能用这种写法,type会报错,直接用next覆盖:
a=a.next #head不变,why???
else:
a.next=a.next.next #head变,把重复的点跳过
# head.display()
# print('/n/')
# a.display()
return head
#eg:变化过程
# 1!=2 2!=1 1=1
#head 1211 1211 1211 121(why???)
#a 1211 211 11 1
head=ListNode(1)
head.next=ListNode(2)
head.next.next=ListNode(1)
head.next.next.next=ListNode(1)
head.next.next.next.next=ListNode(1)
ans=Solution().deleteDuplicates(head)
ans.display()