剑指offer 56. 删除链表中重复的结点

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

思路:

是有两个循环判断的控制,上一个是主要对应2 - 3 - 4这种情况的,可以很快的把头指针移过来,下面这个循环是对应
存在相同值的,不断循环找下一个值。

参考答案:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteDuplication(self, pHead):
        # write code here
        if pHead is None or pHead.next is None:
            return pHead
        start = head = ListNode(-1)
        head.next = pHead
        while pHead and pHead.next:
            if pHead.val == pHead.next.val:
                val = pHead.val
                while pHead and val == pHead.val:
                    pHead = pHead.next
                start.next = pHead
            else:
                start = pHead
                pHead = pHead.next
        return head.next

        
    

思路二:

将链表里面所有的数存在一个列表里面,然后把列表里面只出现一次的数提取出来,在新建一个链表放进去。

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def deleteDuplication(self, pHead):
        # write code here
        res = []
        while pHead:
            res.append(pHead.val)
            pHead = pHead.next

        # filter函数和map相似,但是filter是返回布尔值去去输入列表进行判断
        res = list(filter(lambda c: res.count(c) == 1, res))

        newlist = ListNode(0)
        pre = newlist
        for i in res:
            node = ListNode(i)
            pre.next = node
            pre = pre.next
        return newlist.next

Note

  • 尤其注意Python下链表的创建,已经吃了无数次亏了;

  • 这道题中,while pHead and pHead.next:

    val = pHead.val
    while pHead and val == pHead.val:
    	pHead = pHead.next
    start.next = pHead
    

    都很值得学习。

  • 注意返回计数只为1或者>1的条件判断式:

    	# filter函数和map相似,但是filter是返回布尔值去去输入列表进行判断
    	res = list(filter(lambda c: res.count(c) == 1, res))
    

    即:注意filter表达式的用法。

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/84504414