1. 程式人生 > >鏈表問題(3)-----反轉

鏈表問題(3)-----反轉

復雜 思路 def 代碼 list __init__ fir ast eve

1、題目:反轉單鏈表或雙鏈表

要求:如果鏈表長度為N,時間復雜度為O(N),額外的空間復雜度為O(1)

反轉單鏈表的思路:

1 → 2 → 3 → 4 → 5

(1)first = head = 1

循環:

   temp = head.next 2

head.next = temp.next 1 → 3

temp.next = first 2 →1

first = temp 2 【此時的頭結點是2】

代碼:

class Node:
    def __init__(self,value):
        self.value 
= value self.next = None def reverseList(head): if not head: return head first = head while head.next: temp = head.next head.next = head.next.next temp.next = first first = temp return first head = Node(1) head.next = Node(2) head.next.next
= Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) reverseList(head)

反轉雙鏈表的思路:

只要將每個節點的 next 和 last 互換就可以了。

代碼:

class Node:
    def __init__(self,value):
        self.value = value
        self.next = None
def reverseList(head):
    if not head:
        return head

#重點
    while
head: head.next , head.last = head.last,head.next head = head.last return head head = Node(1) head.last = None head.next = Node(2) head.next.last = head head.next.next = Node(3) head.next.next.last = head.next head.next.next.next = Node(4) head.next.next.next.last = head.next.next head.next.next.next.next = Node(5) head.next.next.next.next.last = head.next.next.next reverseList(head)

鏈表問題(3)-----反轉