反转链表 python 递归_LeetCode 206.反转链表(Python3)
題目:
反轉(zhuǎn)一個(gè)單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進(jìn)階:
你可以迭代或遞歸地反轉(zhuǎn)鏈表。你能否用兩種方法解決這道題?
解答:
方法一:原地反轉(zhuǎn)。
# 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':
# cur當(dāng)前節(jié)點(diǎn)
# pre為當(dāng)前節(jié)點(diǎn)的上一個(gè)節(jié)點(diǎn),反轉(zhuǎn)后的下一個(gè)節(jié)點(diǎn)
# nex為當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn),反轉(zhuǎn)后的上一個(gè)節(jié)點(diǎn)
cur = head
pre = None
while cur:
# 節(jié)點(diǎn)原地反轉(zhuǎn)
nex = cur.next
cur.next = pre
pre = cur
# 進(jìn)入下一個(gè)要反轉(zhuǎn)的節(jié)點(diǎn)
cur = nex
return pre
總結(jié)
以上是生活随笔為你收集整理的反转链表 python 递归_LeetCode 206.反转链表(Python3)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: r语言echarts画箱线图_R语言之数
- 下一篇: python基本判断语句_python基