1. 程式人生 > 其它 >Day1 反轉連結串列【連結串列】【存疑】

Day1 反轉連結串列【連結串列】【存疑】

技術標籤:劍指offer

題目:
定義一個函式,輸入一個連結串列的頭節點,反轉該連結串列並輸出反轉後連結串列的頭節點。

思路:
先將原連結串列的value按順序存入陣列l中,再用陣列的pop()方法,新建ListNode節點(陣列中的value作為x輸入),達到反轉效果。
需注意:進行反轉前,要先標記頭節點,直接反轉會找不到頭節點。

程式碼:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution: def reverseList(self, head: ListNode) -> ListNode: if head is None: return None p=head l=[] while p: l.append(p.val) p=p.next newhead=node=ListNode(l.pop()) while l: node.next=ListNode(
l.pop()) node=node.next return newhead

企圖優化:
陣列中可以直接存ListNode節點
(原始碼做法:陣列中存放.val,再依據val新建ListNode節點)
原始碼執行效果
在這裡插入圖片描述

可以看到優化後,雖然消耗記憶體變少,但耗時增加不少(優化了個寂寞)。下面是企圖優化的程式碼
注意一定要加倒數第二行的 【node.next=None】不然會超出時間限制。原來的程式碼不用加這句是因為,新建ListNode節點 初始化時,預設self.next=None。而原節點的node.next是有值的,必須用None再覆蓋掉原值,不然會打架

# Definition for singly-linked list.
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if head is None: return None p=head l=[] while p: l.append(p) p=p.next newhead=node=l.pop() while l: node.next=l.pop() node=node.next node.next=None return newhead

錯誤程式碼:
只輸出頭節點的值,而非整個連結串列。為啥?

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        p=head
        l=[]
        while p:
            l.append(p.val)
            p=p.next
        n=len(l)
        while l:
            if len(l)==n:
                newhead=node=ListNode(l.pop())
            else:
                node=ListNode(l.pop())
            node=node.next
        return newhead