python实现链表的删除_用动画来看Python如何实现链表的逆序(一)

用动画来看Python如何实现链表的逆序(一)[1]

  • 1 创建链表

  • 2 逆序算法主体

  • 3 程序主体

  • 4 算法性能分析

1 创建链表

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

2 逆序算法主体

def Reverse(head):    """    :function: 对带头单链表进行逆序    :param head: 链表头结点    :return: None    """    # 判断链表是否为空    if head==None or head.next==None:        return    pre = None  # 前驱结点    cur = None  # 当前结点    next = None # 后继结点
    # 把链表首结点变成尾结点    cur = head.next    next = cur.next    cur.next = None    pre = cur    cur = next

59b1b31a83dfaf69799dca4e3b9062c5.gif

    # 使当前遍历到的结点cur指向其前驱结点    while cur.next != None:        next = cur.next        cur.next = pre        pre = cur        cur = next
0c6ae1fb4ab8c3db2bc28972ebd7c69c.gif
    # 链表最后一个结点指向倒数第二个结点    cur.next = pre    # 链表头结点指向最后一个结点    head.next = cur
31ec7256956267ee3eaebe955036e39a.gif

3 程序主体

if __name__ == "__main__":    # 定义单链表    link_index = 1    head = LNode()    head.next = None    tmp = None    cur = head    while link_index <= 4:        tmp = LNode()        tmp.data = link_index        tmp.next = None        cur.next = tmp        cur = tmp        link_index += 1    print("逆序前:")    # 遍历单链表    cur = head.next    while cur != None:        print(cur.data)        cur = cur.next    print("逆序后:")        # 调用逆序方法    Reverse(head)        # 遍历单链表    cur = head.next    while cur != None:        print(cur.data)        cur = cur.next
ba80bc47ace7336ab8629069f43f93e9.gif

4 算法性能分析

以上这种方法只需要对链表进行一次遍历,因此,时间复杂度为O(n),其中,N为链表的长度。但是需要常数个额外的变量来保存当前结点的前驱结点与后继结点,因此,空间复杂度为O(1)。

参考资料

[1]

摘自: 《Python程序员面试算法宝典》

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值