链表

class LinkNode(object):
    def __init__(self, value=None, next=None):
        self.value = value
        self.next = next


class Link(object):
    def __init__(self):
        self.head = None

    def isempty(self):
        return self.head == None

    def add(self, value):
        # add在头部添加
        new_node = LinkNode(value)
        new_node.next = self.head
        self.head = new_node

    def append(self, value):
        # append(item) 链表尾部添加元素
        new_node = LinkNode(value)
        if not self.head:
            self.head = new_node
        else:
            copy_head = self.head
            while copy_head.next:
                copy_head = copy_head.next
            copy_head.next = new_node

    def insert(self, index, value):
        # insert(pos, item) 指定位置添加元素
        new_node = LinkNode(value)
        if 0 < index <= len(self.travel()):
            count = 0
            copy_head = self.head
            while copy_head:
                count += 1
                if count == index:
                    break
                copy_head = copy_head.next
            new_node.next = copy_head.next
            copy_head.next = new_node
        elif index == 0:
            self.add(value)
        else:
            self.append(value)

    def travel(self):
        copy_head = self.head
        nodes = []
        while copy_head:
            nodes.append(copy_head.value)
            copy_head = copy_head.next
        return nodes

    def length(self):
        return len(self.travel())

    def search(self, value):
        return value in self.travel()

    def remove(self, value):
        if self.search(value):
            copy_head = self.head
            if copy_head.value == value:
                self.head = self.head.next
                return True, '删除成功'
            while copy_head.value != value:
                if copy_head.next.value == value:
                    copy_head.next = copy_head.next
                    return True, '删除成功'
                copy_head = copy_head.next
        return False, '元素不存在'

    def __repr__(self):
        nodes = self.travel()
        return '开头' + '->'.join(nodes) + '结尾'


link = Link()
link.isempty()
link.append('a')
link.append('c')
link.append('d')
link.add('1')
link.insert(2, '2')
link.remove('a')
print(link.travel())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值