python——Leetcode 83. 删除排序链表中的重复元素

题目

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

示例 1:

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

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

解题思路

另外使用两个指针b,n,n指向要判断的结点,b指向它的前一个结点。由于第一个结点肯定不会跟前面的重复,所以从第二个结点开始判断,初始化b = head,n=head.next,代码如下:

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

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

猜你喜欢

转载自blog.csdn.net/lwycc2333/article/details/80534899