【LeetCode每天一題】Reverse Linked List(鏈表反轉)
阿新 • • 發佈:2019-03-23
指向 -s sin ive n) 空間 col 鏈表 info
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?
解決思路:使用原地改變鏈表的指針進行反轉。時間復雜度為O(n),空間復雜度為O(1). 流程圖如下:
1 class Solution(object):
2 def reverseList(self, head):
3 """
4 :type head: ListNode
5 :rtype: ListNode
6 """
7 pre = None # 定義前驅節點
8 cur = head # 定義後驅節點
9 while cur: # 當cur為空時,循環結束
10 tem = cur.next # 使用臨時變量保存下一個節點
11 cur.next = pre # 指向前驅節點
12 pre = cur # 前驅節點復制到當前節點
13 cur = tem # 臨時變量進行復制
14 return pre
【LeetCode每天一題】Reverse Linked List(鏈表反轉)