83. Remove Duplicates from Sorted List

时间:2021-06-22 07:35:46

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

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 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
        """
        if head == None:
            return head
        cur = head
        pre = head
        #pre和cur同指向头结点,cur一直走,直到cur和pre值不相同,删除重复的节点,并且pre指向cur的结点
        while cur != None:
            if pre.val != cur.val:
                pre.next = cur
                pre = cur
            cur = cur.next
        #用于去掉结尾的重复值
        pre.next = cur
        return head