[LeetCode] 206. Reverse Linked List_Easy tag: Linked List
2019-04-30 03:14 Johnson_强生仔仔 阅读(212) 评论(0) 编辑 收藏 举报Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
很基本的一道换顺序的题目,先建一个pre 指针,设为None,然后将head.next 存到temp node中,然后将head.next 指针指向pre,接着再将pre和head都依次后移一位。
Code:
1) Basic, using temp node
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head): pre = None while head: temp = head.next head.next = pre pre = head head = temp return pre
2) 利用python可以多重赋值
class Solution: def reverseList(self, head): pre = None while head: head.next, pre, head = pre, head, head.next return pre