206. 反转链表
2019-05-09 本文已影响0人
好吃红薯
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
stack = []
while head:
stack.append(head.val)
head = head.next
res = ListNode(None)
p = res #此时 p 和res 共享数据和地址
while stack:
p.next = ListNode(stack[-1])
stack.pop()
p = p.next #此时 p 的数据和地址都为p.next,与res
return res.next