首页 > 其他 > 详细

83. Remove Duplicates from Sorted List

时间:2018-11-29 13:21:19      阅读:119      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/boluo007/p/10037547.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!