Python之双向链表

双向链表是除头和尾以外,头指针指向前一节点,尾指针指向后一节点

python实现

#定义双向链表
class ListNode():
    def __init__(self,data):
        self.head = None
        self.data = data
        self.next = None

#判断是否为空
def isempty(self):
    return self.data == None

#尾部插入元素
def nodes_tail(self,data):
    if isempty(self):
        self.data = data
    else:
        node = ListNode(None)
        node.data = data
        p = self
        while p.next is not None:
            p = p.next
        p.next = node
        node.head = p
#首部插入元素
def nodes_head(self,data):
    if isempty(self):
        self.data = data
        return self
    else:
        node = ListNode(None)
        node.data = data
        node.next = self
        self.head = node
        return node
#在中间插入节点
def nodes_insert(self,data,num):
    if isempty(self) and num == 1:
        self.data = data
    else:
        node = ListNode(None)
        node.data = data
        p = self
        num = num-2
        while num and p.next is not None:
            print(num)
            p = p.next
            num = num - 1
        node.next = p.next
        node.head = p
        p.next.head = node
        p.next = node
#删除中间节点元素
def nodes_remove(self,num):
    if num == 1:
        return False
    else:
        p = self
        num = num - 1
        while num and p.next is not None:
            p = p.next
            num -= 1
        if num == 0:
             p.next.head = p.head
             p.head.next = p.next
             return True
        else:
            return False

if __name__ == '__main__':
    nodelist = ListNode(None)
    for i in range(5):
        nodes_tail(nodelist,i)
    nodelist = nodes_head(nodelist,10)
    nodes_insert(nodelist,9,2)
    nodes_remove(nodelist,2)
    p = nodelist
    #正序输出
    while True:
        print(p.data)
        if p.next == None:
            break
        else:
            p = p.next
    #逆序输出
'''
    while True:
        print(p.data)
        if p.head == None:
            break
        else:
            p = p.head

'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值