给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
思路:遍历链表,重复值的节点只保留一个。
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head:ListNode)->ListNode:
pre=head
cur=None
new=None
while(pre):
curval=pre.val
tmp=pre
pre=pre.next
no=1
while(pre!=None and pre.val==curval):
no+=1
pre=pre.next
if(cur):
tmp.next=None
cur.next=tmp
cur=cur.next
else:
tmp.next=None
cur=tmp
new=cur
return new
if __name__=="__main__":
head=ListNode(1)
last=head
for i in[1]:
last.next=ListNode(i)
last=last.next
print(Solution().deleteDuplicates(head))