Leetcode-Remove Duplicates from Sorted List-Python

Remove Duplicates from Sorted List

从排序链表中删除重复元素。
Description

解题思路
依次比较相邻的两个链表元素,若值相等,则将前一个节点的next引用为后一个节点的后一个节点。使用cur来依次向下遍历元素,最后返回head。

# 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
        """
        cur = head

        while cur:
            while cur.next and cur.next.val==cur.val:
                cur.next = cur.next.next
            cur = cur.next
        return head

猜你喜欢

转载自blog.csdn.net/ddydavie/article/details/77478598