“”“
给定一个带头结点的单链表,请将其逆序。即如果单链表原来为 head -> 1 -> 2 -> 3 ->4 -> 5 -> 6 -> 7,那么逆序后变为head -> 7 -> 6 -> 5 ->4 -> 3 -> 2 -> 1。
”“”
方法一:就地逆序
class LNode:
def __init__(self,data):
self.data = data
self.next = None
def reverse(head):
# 特殊情况:头节点为空或者为单节点,直接返回
if head is None or head.next is None:
return head
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 = cur.next
cur= next
# 链表中最后一个节点指到倒数第二个节点
cur.next = pre
# 将链表的头节点知道原链表的尾节点
head.next = cur
if __name__ == "__main__":
i = 1
#链表的头结点
head = LNode(0)
cur = head
#构造单链表
while i<