该题目类似于leetcode206题目,只不过输出格式不同 ,leetcode是返回头指针,而本题目输出整个数组,贴上测试样例
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def printListReversingly(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
if not head:
return []
cur=head
# pre存储的是逆置之后的链表节点,
# lat是cur的后面一个节点
pre=None
count=0
# 遍历到结尾
while cur:
lat=cur.next
cur.next=pre
# pre向后移动
pre=cur
# cur向后移动
cur=lat
count+=1
result=[]
for i in range(count):
result.append(pre.val)
pre=pre.next
return result
# 返回链表头指针
def init_linklist(data, num_data):
head = LinkNode(None)
point = head
for i in range(num_data):
point.next = LinkNode(data[i])
point = point.next
return head.next
data = [1, 2, 3, 4, 5]
num_data = len(data)
solu = Solution()
head = init_linklist(data, num_data)
result=solu.printListReversingly(head)
print(result)