leetcode刷題--Reverse Linked List

黃思喆發表於2015-06-01

題目:返回一個單連結串列的反向單連結串列

這道題程式碼如下: 只要想清楚開始的狀況和結束時的狀況就好了

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

class Solution:
    # @param {ListNode} head
    # @return {ListNode}
    def reverseList(self, head):
        before = None
        while head != None:
            temp = head.next
            head.next = before
            before = head
            head = temp
        return before 

也可以利用python中list的特性:

程式碼:

class Solution:
    # @param {ListNode} head
    # @return {ListNode}
    def reverseList(self, head):
        if head == None:
            return head
        temp=[]
        node = head
        while node != None:
            temp.append(node)
            if node.next != None:
                node=node.next
            else:
                break
        temp.reverse()
        for i in range(len(temp)):
            if i ==len(temp)-1:
                temp[i].next= None
            else:
                temp[i].next= temp[i+1]
        return temp[0]

相關文章