首页 > 代码库 > Leetcode_num11_Remove Duplicates from Sorted List

Leetcode_num11_Remove Duplicates from Sorted List

题目:

Given a sorted linked list, delete all duplicates such that each element appear only once.

这道链表的题也比较简单,目标是为了去重,只是需要注意在去重的过程中使用while循环(而非if),使某一个节点的下一个节点必须指向与其不同的节点

上代码咯

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

class Solution:
    # @param head, a ListNode
    # @return a ListNode
    def deleteDuplicates(self, head):
        node=head
        while(node):
            while(node.next!=None)and(node.next.val==node.val):#直至下一节点不同或为空
                node.next=node.next.next
            node=node.next
        return head


Leetcode_num11_Remove Duplicates from Sorted List