美文网首页
链表 Leetcode 206 反转列表

链表 Leetcode 206 反转列表

作者: 禾木清清 | 来源:发表于2019-07-13 06:55 被阅读0次

题目

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

在真实的面试中遇到过这道题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

  • 使用pre记录前一个点
  • 使用curr记录当前的节点
  • 循环head, 使用curr保存头节点, head后移,curr指向pre, pre = curr
    这样就遍历反转了链表

代码

# 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
        """
        pre = None
        curr = None
        
        while head:
            curr = head
            head = head.next
            curr.next = pre
            pre = curr
        return pre
            

相关文章

网友评论

      本文标题:链表 Leetcode 206 反转列表

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