LeetCode——第八十三题(python):删除排序链表中的重复元素

题目
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例1
输入: 1->1->2
输出: 1->2

示例2
输入: 1->1->2->3->3
输出: 1->2->3

运行成功的代码

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        p1=head
        
        if not head:
            return None
        p2=p1.next
        while p2:
            if p1.val==p2.val:
                p2=p2.next
            else:
                p1.next=p2
                p1=p2
                p2=p2.next
        p1.next =None
        return head

运行结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45398231/article/details/104886118