• python


      不允许使用额外数据结构。
      代码:

    class Node:
        def __init__(self, data=None):
            self.next = None
            self.data = data
    
        def get_data(self):
            return self.data
    
        def get_next(self):
            return self.next
    
        def remove_after(self):
            self.next = self.next.next
    
    
    class LinkedList:
        def __init__(self):
            self.__head = None
    
        def __str__(self):
            p = self.__head
            res = []
            while p:
                if p.get_data():
                    res.append(p.get_data())
                p = p.get_next()
            return '[' + ', '.join([str(_) for _ in res]) + ']'
    
        def get_head(self):
            return self.__head
    
        def add_node(self, node: Node):
            if not self.__head:
                self.__head = node
            else:
                p = self.__head
                while p.get_next():
                    p = p.get_next()
                p.next = node
    
    
    def remove_duplicates(linkedlist: LinkedList):
        p = linkedlist.get_head()
        q = p.get_next()
        d = {p.get_data(): True}
        while p and q:
            if q.get_data() in d:
                p.remove_after()
                q = p.get_next()
                continue
            elif q.get_data():
                d[q.get_data()] = True
            p = p.get_next()
            q = p.get_next()
    
    
    l = LinkedList()
    l.add_node(Node(1))
    l.add_node(Node(2))
    l.add_node(Node(1))
    l.add_node(Node(2))
    l.add_node(Node(1))
    
    print(l)
    remove_duplicates(l)
    print(l)
    

      输出:

    [1, 2, 1, 2, 1]
    [1, 2]
    

      

  • 相关阅读:
    学习计划 23月
    bash学习笔记
    bash 中 while读取文件并通过 ssh执行命令出现的问题及解决方法
    bash 学习笔记2
    fedora 启动 openssh
    lesson5 键盘的应用
    第十三章 int指令
    第十五章 外中断
    第十二章 内中断
    第十四章 端口
  • 原文地址:https://www.cnblogs.com/darkchii/p/13208422.html
Copyright © 2020-2023  润新知