美文网首页
206. 反转链表

206. 反转链表

作者: 好吃红薯 | 来源:发表于2019-05-09 15:38 被阅读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

相关文章

网友评论

      本文标题:206. 反转链表

      本文链接:https://www.haomeiwen.com/subject/drgwoqtx.html