天天看点

《剑指Offer》刷题之删除链表中重复的结点

《剑指Offer》刷题之删除链表中重复的结点

我不知道将去向何方,但我已在路上!
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 !
  • 题目:

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

  • 示例:
示例 1 :
输入:{1,2,3,3,4,4,5}
返回值:{1,2,5}
           
  • 代码1:
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteDuplication(self, pHead):
        temp = []
        while pHead:
            temp.append(pHead.val)
            pHead = pHead.next
        temp = list(filter(lambda c:temp.count(c)==1,temp))
        result = ListNode(None)
        pre = result
        for i in temp:
            node = ListNode(i)
            pre.next = node
            pre = pre.next
        return result.next
           
  • 算法说明:

    遍历链表,把所有的元素存入列表

    temp

    通过

    filter

    lambda

    函数过滤掉次数超过1的元素;

    建立新的链表

    result

    ,将其复制给

    pre

    ,目的是保存头节点;

    pre

    temp

    中的元素加入链表;

    返回结果

    result.next

继续阅读