单链表(Python)

Posted guguda

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单链表(Python)相关的知识,希望对你有一定的参考价值。

链表——增删改查

class Node():
    def __init__(self, item):
        self.item = item
        self.next = None
class Link():
    def __init__(self):
        #构造一个空链表
        #head存储只能是空或者第一个节点的地址
        self._head = None
    #头插
    def add(self, item):
        #创建一个新的结点
        node = Node(item)
        node.next = self._head
        self._head = node
    #遍历
    def travel(self):
        #_head在链表创建好后一定不可变
        if self.isEmpty():
            print("空链表")
            return
        cur = self._head
        while cur:
            print(cur.item)
            cur = cur.next
    def isEmpty(self):
        return self._head == None
    def size(self):
        cur = self._head
        count = 0
        while cur:
            count += 1
            cur = cur.next
        return count
    def append(self, item):
        node = Node(item)
        if self._head == None:
            self._head = node
            return
        cur = self._head
        pre = None
        while cur:
            pre = cur
            cur = cur.next
        pre.next = node
    def search(self,item):
        flag = False
        cur = self._head
        while cur:
            if cur.item == item:
                flag = True
                break
            cur = cur.next
        return flag
    def insert(self,pos,item):
        node = Node(item)
        pre = None
        cur = self._head
        for i in range(pos):
            pre = cur
            cur = cur.next
        pre.next = node
        node.next = cur
    def remove(self,item):
        cur = self._head
        pre = None
        if cur.item == item:
            self._head = cur.next
            return
        while cur:
            pre = cur
            cur = cur.next
            if cur.item == item:
                pre.next = cur.next
                return

link1= Link()
link1.travel()
link1.append(1)
link1.append(3)
link1.append(4)
link1.travel()

print(link1.search(3))
print(link1.search(4))
link1.insert(1, 2)
link1.remove(4)
link1.travel()
# 空链表
# 1
# 3
# 4
# True
# True
# 1
# 2
# 3

以上是关于单链表(Python)的主要内容,如果未能解决你的问题,请参考以下文章

python用单链表写一个通讯录,包括添加,删除(可恢复),查找等基本功能

python数据结构之单链表

Python线性表——单链表

python 单链表操作

用最简单的方式学Python单链表

python实现数据结构单链表