用动画来看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
# 使当前遍历到的结点cur指向其前驱结点 while cur.next != None: next = cur.next cur.next = pre pre = cur cur = next
# 链表最后一个结点指向倒数第二个结点 cur.next = pre # 链表头结点指向最后一个结点 head.next = cur
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
4 算法性能分析
以上这种方法只需要对链表进行一次遍历,因此,时间复杂度为O(n),其中,N为链表的长度。但是需要常数个额外的变量来保存当前结点的前驱结点与后继结点,因此,空间复杂度为O(1)。
参考资料
[1]摘自: 《Python程序员面试算法宝典》