插入法:从链表的第二个节点开始,把遍历到的节点插入到头结点的后面,直到遍历结束
class LNode:
def __init__(self):
self.data = None
self.next = None
def Reverse(head):
if head == None or head.next == None:
return
cur = None
nex = None
cur = head.next.next
head.next.next = None
while cur is not None:
nex = cur.next
cur.next = head.next
head.next = cur
cur = nex
if __name__ == '__main__':
i = 1
head = LNode()
head.next = None
temp = None
cur = head
#构造单链表
while i<8:
temp = LNode()
temp.data = i
temp.next = None
cur.next = temp
cur = temp
i += 1
print('逆序前:',end='')
cur = head.next
while cur != None:
print(cur.data,end=' ')
cur = cur.next
print('\n逆序后:',end='')
Reverse(head)
cur = head.next
while cur != None:
print(cur.data,end=' ')
cur = cur.next