天天看點

【單連結清單】反轉連結清單

【題】:給你單連結清單的頭節點 

head

 ,請你反轉連結清單,并傳回反轉後的連結清單。

【分析】:

一種解決方案是

按原始順序疊代結點

,并将它們

逐個移動到清單的頭部

。似乎很難了解。我們先用一個例子來說明我們的算法。

算法概述

讓我們看一個例子:

【單連結清單】反轉連結清單

請記住,黑色結點 23 是原始的頭結點。

1. 首先,我們将黑色結點的下一個結點(即結點 6)移動到清單的頭部:

【單連結清單】反轉連結清單

2. 然後,我們将黑色結點的下一個結點(即結點 15)移動到清單的頭部:

【單連結清單】反轉連結清單

3. 黑色結點的下一個結點現在是空。是以,我們停止這一過程并傳回新的頭結點 15。

連結:https://leetcode-cn.com/leetbook/read/linked-list/fx61e/

【代碼】:

class ListNode(object):
     def __init__(self, val=0, next=None):
         self.val = val
         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        else:
            if not head.next:
                return head
            else:
                pre = head
                cur = head.next
                while cur:
                    behind = cur.next
                    cur.next = pre
                    #此處為将頭結點的next置為None,即将頭結點置為尾節點
                    if pre == head:
                        pre.next = None
                    pre = cur
                    if not behind:
                        return cur
                    cur = behind
           

繼續閱讀