码迷,mamicode.com
首页 > 编程语言 > 详细

单链表(Python)

时间:2020-06-25 10:03:37      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:==   __init__   search   end   bre   增删改查   第一个   break   创建   

链表——增删改查

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)

标签:==   __init__   search   end   bre   增删改查   第一个   break   创建   

原文地址:https://www.cnblogs.com/gugu-da/p/13190936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!