如何实现链表的逆序
方法一:就地逆序
算法思想:在遍历链表的时候,修改当前节点的指针域的指向,让它指向它的前驱节点。因此,需要一个指针来保存它的前驱,此外,为了调整当前节点的指针域的指向后还能找到后继结点,还需要另外一个指针变量保存后继结点,在所有的节点都被保存好以后,就可以直接完成逆序了
算法性能分析:
这种方法对链表遍历一次,时间复杂度为o(N),N为链表的长度。但是需要常数个变量来保存当前节点、前驱节点和后继节点,因此空间复杂度为o(1)
class LNode:
def __init__(self, x):
self.data = x
self.next = None
def Reverse(head):
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
while cur.next != None:
next = cur.next
cur.next = pre
pre = cur
cur = next
cur.next = pre
head.next = cur
if __name__ == "__main__"