python 链表_Python成为专业人士笔记–自定义链表

“专业人士笔记”系列目录:

创帆云:Python成为专业人士笔记--强烈建议收藏!每日持续更新!​zhuanlan.zhihu.com
python 链表_Python成为专业人士笔记–自定义链表_第1张图片

概述

链表是节点的集合,每个节点由一个索引和一个值组成,索引将所有节点串成了一个序列。自定义链表可用于实现更为复杂的数据结构,如列表、堆栈、队列和关联数组等。

自定义链表建立

本例使用与内置list对象相同的许多方法实现了一个链表

#元素节点处理类
class Node:
    def __init__(self, val):
        self.data = val
        self.next = None


    def getData(self):
        return self.data


    def getNext(self):
        return self.next


    def setData(self, val):
        self.data = val


    def setNext(self, val):
        self.next = val

#链表类
class LinkedList:

    def __init__(self):
        self.head = None


    def isEmpty(self):
        """ 检查链表是否为空 """
        return self.head is None

    def add(self, item):
        """ 将对象添加到链表中 """
        new_node = Node(item)
        new_node.setNext(self.head)
        self.head = new_node


    def size(self):
        """返回链表的长度"""
        count = 0
        current = self.head

        while current is not None:
            count += 1
            current = current.getNext()
        return count


    def search(self, item):
        """ 在链表中搜索项目。如果找到,返回True。如果没有找到,返回False """
        current = self.head
        found = False

        while current is not None and not found:
            if current.getData() is item:
                found = True

            else:
                current = current.getNext()
            return found


    def remove(self, item):
        """ 从链表中删除项目。如果在链表中没有找到项目,则引发ValueError """
        current = self.head
        previous = None
        found = False

        while current is not None and not found:

            if current.getData() is item:
                 found = True

            else:
                previous = current
                current = current.getNext()

        if found:

            if previous is None:
                self.head = current.getNext()

            else:
                previous.setNext(current.getNext())

        else:
            print('未找到值')
            raise ValueError




    def insert(self, position, item):
        """
         在指定的位置插入项目。如果指定的位置超出界限,则引发IndexError 
        """
        if position > self.size() - 1:
            print("Index out of bounds.")
            raise IndexError

        current = self.head
        previous = None
        pos = 0

        if position is 0:
            self.add(item)
        else:
            new_node = Node(item)

        while pos < position:
            pos += 1
            previous = current
            current = current.getNext()
        previous.setNext(new_node)
        new_node.setNext(current)


    def index(self, item):
        """
        返回找到项目的索引。如果没有找到项目,则返回None。 
        """
        current = self.head
        pos = 0
        found = False

        while current is not None and not found:
            if current.getData() is item:
                found = True
            else:
                current = current.getNext()
                pos += 1

        if found:
            pass
        else:
            pos = None

        return pos


    def pop(self, position=None):
        """
        如果没有提供参数,则返回并删除头部的项。如果提供了位置,则返回并删除该位     置的项。如果索引越界,则引发IndexError 
         """

        if position > self.size():

            print('Index out of bounds')
            raise IndexError

        current = self.head

        if position is None:
            ret = current.getData()
            self.head = current.getNext()

        else:
            pos = 0
            previous = None

            while pos < position:
                previous = current
                current = current.getNext()
                pos += 1
                ret = current.getData()
                previous.setNext(current.getNext())

        print(ret)

        return ret


    def append(self, item):
        """ 将项追加到链表的末尾 """
        current = self.head
        previous = None
        pos = 0
        length = self.size()

        while pos < length:
            previous = current
            current = current.getNext()
            pos += 1

        new_node = Node(item)

        if previous is None:
            new_node.setNext(current)
            self.head = new_node

        else:
            previous.setNext(new_node)


    def printList(self):
        """打印链表"""
        current = self.head

        while current is not None:

            print(current.getData())
            current = current.getNext()

#函数调用
#使用函数过程非常类似于内置list列表
ll = LinkedList()
ll.add('l') #注意函数,头部增加
ll.add('H')
ll.insert(1,'e') #指定位置添加
ll.append('l') #尾部增加
ll.append('o')
ll.printList()

#输出结果:
 H
 e
 l
 l
 o

请仔细研究并在python3云环境中测试上面的代码, 如果参照以上代码已经完整实现了链表建立和操作方法,那么完全可以基于此建立自定义堆栈、队列等更复杂的数据结构

今天的分享就到这里,禁止转载,违者必究

你可能感兴趣的:(python,链表,python链表,在类里定义一个数组)