1. 程式人生 > >leetcode 206. 反轉連結串列 (Easy)(連結串列)

leetcode 206. 反轉連結串列 (Easy)(連結串列)

題目:      

反轉一個單鏈表。

示例:

輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL

思路:

       需要記錄當前節點,前一個節點,以及後一個節點。首先,初始化一個空節點,空節點是第一個pre節點,head節點是第一個cur節點,head.next是第一個nex節點。將cur的next指標指向pre節點(cur的前一個節點),直到nex節點是空節點。

程式碼:

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

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return None
        if head.next == None:
            return head
        H = None
        pre = H
        cur = head
        nex = head.next
        while nex != None:
            cur.next = pre
            pre = cur
            cur = nex 
            nex = nex.next
        cur.next = pre
        return cur