栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python中无序Linkedlist(链表)双while去重

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python中无序Linkedlist(链表)双while去重

思路就是第一个循环拿到第一个node,第二个循环去和除了第一个node外的所有node对比,碰到值相等的node就进行指针跳过从而实现删除

实现函数:

def remove_duplicates(link_list):
    outside = link_list.get_head()
    while outside:
        inside = outside
        while inside:
            if inside.get_next() is not None and outside.get_data() == inside.get_next().get_data():
                inside.remove_after()
            else:
                inside = inside.get_next()
        outside = outside.get_next()

例子:

list4 = LinkedList()
element_list = [10, 13, 13, 5, 13, 13, 42, 1, 5, 6, 8, 42, 42, 42, 13, 42]
for i in range(len(element_list)-1, -1, -1):
    list4.add(element_list[i])
print(list4)
remove_duplicates(list4)
print(list4)

# 得到结果:
# [10, 13, 13, 5, 13, 13, 42, 1, 5, 6, 8, 42, 42, 42, 13, 42]
# [10, 13, 5, 42, 1, 6, 8]

Node和Linked list class:

class Node(object):
    def __init__(self, data, next_node=None):
        self.__data = data
        self.__next = next_node

    def get_data(self):
        return self.__data

    def set_data(self, data):
        self.__data = data

    def remove_after(self):
        self.__next = self.__next.get_next()

class LinkedList:
    def __init__(self):
        self.__head = None

    def get_head(self):
        return self.__head

    def add(self, item):  # add to the beginning of the list
        new_node = Node(item, self.__head)
        self.__head = new_node

    def __str__(self):
        result_list = []
        if self.__head is not None:
            current = self.__head
            while current is not None:
                result_list.append(str(current.get_data()))
                current = current.get_next()
        return '[' + ', '.join(result_list) + ']'
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/971230.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号