Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

删除链表中的重复数字,注意这里是一旦数字有重复就要把这个数字彻底删除。所以如何彻底删除是一个技术活。当然为了处理头结点被删除的情况,dummy结点也要重出江湖。

在python中,注意在linkedlist中删除某结点并不需要显示删除,而是让前序指向它的后序,跳过该结点。为了便于删除时依然知道前序结点,我们需要一个pre来保存前序,建立连接(尤其是跳过元素的连接)。在每个结点判断其是否和后序结点值相等,如果相等则将所有等于这个值的结点都找到并删除。代码如下:

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        dummy = ListNode(-1)
        dummy.next = head
        prev = dummy
        while head and head.next:
            if head.val == head.next.val:
                while head and head.next and head.val == head.next.val:
                    head = head.next
                head = head.next   #处理最后一个值相等的结点
                prev.next = head
            else:
                prev = prev.next
                head = head.next
        return dummy.next

时间复杂度O(n),空间复杂度O(1)。

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

class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        
        if head is None:
            return head
        
        dummy = ListNode(-1)
        dummy.next = head
        head = dummy
        for i in xrange(m-1):  # m >= 1  
            head = head.next
        
        # now, head is the prevous node of the first needed revesed node.
        pre = head.next # first node
        cur = head.next.next # second node
        
        # reverse the interval pointer direction
        for i in xrange(n-m):
            next = cur.next
            cur.next = pre
            pre = cur
            cur = next 
        
        head.next.next = cur  #cur is the first node after the interval
        head.next = pre # pre is the last node of the interval
        
        return dummy.next

 

posted on 2016-05-30 22:07  Sheryl Wang  阅读(170)  评论(0编辑  收藏  举报

导航