python链表——节点Node与单链表LinkedList构造

单链表的节点,包含值域data与指针next,所以其定义也很简单:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

单链表,包含了头节点head,链表长度size,方法包括了增加add, 删除delete, 插入insert, 打印遍历链表print_link等等,可以根据自己的需要,来写相应的方法,这里只写了几个。

对单链表的操作,最主要的就是对其指针的操作,经常要引入临时变量来存储指针指向的值或者节点。

代码

class LinkedList:
    def __init__(self):
        self.head = None
        self.size = 0

    def add(self, value):
        new_node = Node(value)
        if self.head is None:
            self.head = new_node
            self.size += 1
            return
        p = self.head
        while p.next:
            p = p.next
        p.next = new_node
        self.size += 1

    def delete(self):
        if self.head is None:
            print("The link is None")
            return
        elif self.head.next is None:
            self.head = None
            self.size -= 1
        else:
            cur = self.head
            pre = cur
            while cur.next:
                pre = cur
                cur = cur.next
            pre.next = None
            self.size -= 1

    def insert(self, target, value):
        new_node = Node(value)
        if self.head is None:
            print("The link is None")
            return
        cur = self.head
        while cur.data != target and cur.next:
            cur = cur.next
        if cur.data == target and cur.next:
            new_node.next = cur.next
            cur.next = new_node
            self.size += 1
        elif cur.data == target and cur.next is None:
            cur.next = new_node
            self.size += 1
        else:
            print("Cannot find ", target)
            return

    def print_link(self):
        if self.head is None:
            print("The link is None")
            return
        cur = self.head
        while cur:
            print(cur.data)
            cur = cur.next

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值