题目描述:输入一个链表,反转链表后,输出新链表的表头。
##剑指offer里的测试输入数据是链表类型
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if not pHead or not pHead.next:
return pHead
pre = pHead
cur = pHead.next
next = None
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
pHead.next = None
return pre
##各大公司笔试题的测试输入数据常常是列表,所以我们需要自己将列表转化成链表
class Node():
# 创建一个节点
def __init__(self, val=None, next=None):
self.val = val
self.next = next
# 构建单链表
def constructListNode(array):
if len(array) == 0:
return None
head = Node()
head.val = array[0]
# 暂存头结点
res = head
for i in range(1, len(array)):
temp = Node()
temp.val = array[i]
head.next = temp
head = temp
return res
# 遍历单链表
def ergodicListNode(head):
while head:
print(head.val, end = ' ')
head = head.next
print()
# 反转单链表
def reverseListNode(head):
if not head or not head.next:
return
# 构建前置结点
pre = head
# 构建当前节点
cur = head.next
# 存储当前节点的下个节点
next = Node()
#反转,暂存next
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
head.next = None
return pre
if __name__ == '__main__':
array = input().split()
# 构建单链表测试
head = constructListNode(array)
# 遍历单链表测试
# ergodicListNode(head)
# 反转单链表测试
res = reverseListNode(head)
ergodicListNode(res)