python与算法:创建一个链表,和python原生的list对应,可以根据不同的业务场景选择使用那个

class LNode:
    def __init__(self,elem,next_=None):
        self.elem=elem
        self.next=next_

class LinkedListUnderflow(ValueError):
    pass
        
class LList:
    def __init__(self):
        self._head=None
        
    def is_empty(self):
        '''判断链表是否为空'''
        return self._head is None
    
    def prepend(self,elem):
        '''在链表的最前端加入元素'''
        self._head=LNode(elem,self._head)
        
    def append(self,elem):
        '''在链表的最后端加入元素'''
        if self._head is None:
            self._head=LNode(elem)
            return 
        p=self._head
        while p.next is not None:
            p=p.next
        p.next=LNode(elem)
        
    def insert(self,elem,i):
        '''在链表的中间加入元素'''
        if i==0:
            self.prepend(elem)
        if i>0:
            count=0
            p=self._head
            while count
# 创造一个链表加入元素
mlist1=LList()
for i in range(10):
    mlist1.prepend(i)
for i in range(11,20):
    mlist1.append(i)
mlist1.insert(2222,0)
mlist1.printall()
# 删除index是1的元素
print(mlist1.pop_index(1))
mlist1.printall()
# 查找元素5所在的位置
mlist1.find(5)
# 对所有元素执行add1操作
def add1(x):
    return x+x
mlist1.forall(add1)
mlist1.printall()
# 分析链表的长度
len(mlist1)

python与算法:创建一个链表,和python原生的list对应,可以根据不同的业务场景选择使用那个_第1张图片

你可能感兴趣的:(python,数据结构与算法)