题目:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 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
思路:
遍历字符串,遇见重复项就跳过,不重复就加入新链表.
代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
ans=ListNode(0)
tmp=head
ans.next=head
pre=ans
while tmp and tmp.next:
if tmp.val==tmp.next.val:
tmp=tmp.next
pre.next=tmp
else:
pre=tmp
tmp=tmp.next
return ans.next