Python链表操作

class Node():
    def __init__(self, value=None, next=None):
        self.__value = value
        self.__next = next

    def getValue(self):
        return self.__value

    def getNext(self):
        return self.__next

    def setValue(self, newValue):
        self.__value = newValue

    def setNext(self, nexNext):
        self.__next = nexNext

class Link():
    def __init__(self):
        self.__head = Node()             #头结点,不存放元素,哨兵节点
        self.__tail = None
        self.__length = 0


    def isEmpty(self):
        '''
        判断链表是否为空
        :return:
        '''
        return self.__head.getNext() == None


    def add(self, value):
        '''
        头插法插入元素
        :param value:
        :return:
        '''
        newnode = Node(value, None)
        newnode.setNext(self.__head.getNext())
        self.__head.setNext(newnode)


    def append(self, value):
        '''
        尾插法插入元素
        :param value:
        :return:
        '''
        newnode = Node(value)
        if self.isEmpty():
            self.__head.setNext(newnode)
        else:
            current = self.__head.getNext()
            while current.getNext() != None:
                current = current.getNext()
            current.setNext(newnode)


    def search(self, value):
        '''
        查找链表中是否含有该元素
        :param value:
        :return:
        '''
        current = self.__head
        foundvalue = False
        while current != None and not foundvalue:
            if current.getValue() == value:
                foundvalue = True
            else:
                current = current.getNext()
        return foundvalue

    def index(self, value):
        '''
        查找该元素在链表中的下标位置,
        若没有则返回None
        :param value:
        :return:
        '''
        current = self._head
        count = 0
        found = None
        while current != None and not found:
            count += 1
            if current.getValue() == value:
                return count
        return None

    def print(self):
        '''
        打印链表元素
        :return:
        '''
        current = self.__head.getNext()
        while current != None:
            print(current.getValue())
            current = current.getNext()

    def delete(self, value):
        '''
        删除指定元素
        :param value:
        :return:
        '''
        current = self._head
        while current.getNext() != None and current.getNext().getValue() != value:
            current = current.getNext()
        if current.getNext() == None:
            return 0                    #链表中无此元素,删除失败
        else:
            r = current.getNext()
            current.setNext(r.getNext())
            del r
            return 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值