Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
"""
1->2->3->4->None
new_head
|
None<-4<-3<-2<-1
new_head就是從None開始一直到原來鏈表的尾。
在反轉的時候先記錄下一個節點,然后將當前節點反轉,然后將更新新的表頭,再遍歷下一個節點
"""
def reverseList(self, head: ListNode) -> ListNode:
new_head = None
while head:
# 記錄下一個節點,因為等下反轉當前節點之后就會丟失下一個節點
next_node = head.next
# 反轉當前節點。因為相對于head來說,new_head指向的是head的前一個節點
head.next = new_head
# 更新新的表頭
new_head = head
# 將指針往后移動,這時就需要用到前面記錄的節點
head = next_node
# 最后new_head就是反轉后的表頭
return new_head
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。