83. Remove Duplicates from Sorted List

Posted boluo007

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了83. Remove Duplicates from Sorted List相关的知识,希望对你有一定的参考价值。

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

 

以上是关于83. Remove Duplicates from Sorted List的主要内容,如果未能解决你的问题,请参考以下文章