单链表的创建、增删改查等操作(Python实现)

单链表的创建、增删改查等操作(Python实现)

# 单链表
class Node:
    def __init__(self, elem):
        self.elem = elem
        self.next = None
class SingleLinkedList:

    def __init__(self, length):
        self.head = Node(length)
        self.end = self.head
    def length(self):
        # 求链表长度
        cur = self.head
        count = 0
        while cur.next :
            count += 1
            cur = cur.next
        return count

    def isempty(self):
        # 判断链表是否为空
        return self.head.next == None

    def add(self, elem):
        # 头插法
        node = Node(elem)
        node.next = self.head.next
        self.head.next = node

    def append(self, elem):
        # 尾插法
        node = Node(elem)
        node.next = None
        self.end.next = node
        self.end = node

    def insert(self, loc, elem):
        # 向链表第loc位置插入 数据域 为elem的结点
        cur = self.head
        count = 0
        while cur and count<loc-1:     # 假设只有一个头结点,也可以插入,所以可以进入循环体;所以用cur
            cur = cur.next
            count += 1
        if not cur or count>loc-1:
            print("插入失败")
            return
        node = Node(elem)
        node.next = cur.next
        cur.next = node

    def remove(self, loc):
        # 删除链表第loc位置结点
        cur = self.head
        count = 0
        while cur.next and count<loc-1:   # 假设只有一个头结点,不能删除操作,不能进入循环;所以用cur.next
            cur = cur.next
            count += 1
        if not cur.next or count>loc-1:
            print("删除操作不合法")
            return
        cur.next = cur.next.next
    def travel(self):
        # 遍历链表
        cur = self.head
        while cur.next:
            cur = cur.next
            print(cur.elem)
        if self.isempty():
            print("该链表为空")
    def getelem(self, loc):
        # 获取第loc位置的结点的数据域
        cur = self.head.next
        count = 1
        while cur and count<loc:
            cur = cur.next
            count += 1
        if not cur or count>loc :
            print("不存在")
            return
        print(cur.elem)

    def search(self, elem):
        # 查询链表中 数据域 为elem的结点 第一次出现的位置
        cur = self.head.next
        while cur and cur.elem!=elem:
            cur = cur.next
        if cur and cur.elem==elem:
            print(cur)
            return
        print("不存在")
        pass

def main():
    length = 0
    sll = SingleLinkedList(length)
    print(sll.isempty())
    print(sll.length())
    sll.append(1)
    sll.append(2)
    sll.append(3)
    sll.append(4)
    sll.append(5)
    print(sll.length())
    sll.travel()

main()
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值