leetcode刷題--Reverse Linked List
題目:返回一個單連結串列的反向單連結串列
這道題程式碼如下: 只要想清楚開始的狀況和結束時的狀況就好了
# 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]
相關文章
- Leetcode Reverse Linked List IILeetCode
- leetcode刷題--Remove Linked List ElementsLeetCodeREM
- Leetcode-Reverse Linked List IILeetCode
- Reverse Linked List II leetcode javaLeetCodeJava
- Leetcode 206. Reverse Linked ListLeetCode
- LeetCode - Easy - 206. Reverse Linked ListLeetCode
- 92. Reverse Linked List II
- leetcode刷題--Reverse BitsLeetCode
- 206. Reverse Linked List--LeetCode RecordLeetCode
- 每天一道LeetCode--206. Reverse Linked ListLeetCode
- 資料結構與演算法 | Leetcode 206:Reverse Linked List資料結構演算法LeetCode
- leetcode Linked List CycleLeetCode
- Leetcode Linked List Cycle IILeetCode
- LeetCode Delete Node in a Linked ListLeetCodedelete
- Leetcode Palindrome Linked ListLeetCode
- [leetcode]linked-list-cycle-iiLeetCode
- LeetCode 382 Linked List Random NodeLeetCoderandom
- LeetCode-Palindrome Linked ListLeetCode
- LeetCode-Linked List Random NodeLeetCoderandom
- LeetCode-Odd Even Linked ListLeetCode
- Leetcode-Linked List Cycle IILeetCode
- LeetCode | 141 linked list cycleLeetCode
- [LeetCode] 328. Odd Even Linked ListLeetCode
- 【Leetcode】141. Linked List CycleLeetCode
- LeetCode141:Linked List CycleLeetCode
- 【LeetCode】Flatten Binary Tree to Linked ListLeetCode
- Leetcode Flatten Binary Tree to Linked ListLeetCode
- leetcode141: Linked List CycleLeetCode
- LeetCode之Odd Even Linked List(Kotlin)LeetCodeKotlin
- Leetcode 142. Linked List Cycle IILeetCode
- LeetCode | 203. Remove Linked List ElementsLeetCodeREM
- Leetcode 234. Palindrome Linked ListLeetCode
- Leetcode 203. Remove Linked List ElementsLeetCodeREM
- 【Leetcode】142.Linked List Cycle IILeetCode
- LeetCode142:Linked List Cycle IILeetCode
- Leetcode-Flatten Binary Tree to Linked ListLeetCode
- Flatten Binary Tree to Linked List leetcode javaLeetCodeJava
- [LeetCode] 2487. Remove Nodes From Linked ListLeetCodeREM