反转链表 python 递归_LeetCode 206.反转链表(Python3)
生活随笔
收集整理的這篇文章主要介紹了
反转链表 python 递归_LeetCode 206.反转链表(Python3)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?
解答:
方法一:原地反轉。
# 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當前節點
# pre為當前節點的上一個節點,反轉后的下一個節點
# nex為當前節點的下一個節點,反轉后的上一個節點
cur = head
pre = None
while cur:
# 節點原地反轉
nex = cur.next
cur.next = pre
pre = cur
# 進入下一個要反轉的節點
cur = nex
return pre
總結
以上是生活随笔為你收集整理的反转链表 python 递归_LeetCode 206.反转链表(Python3)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: r语言echarts画箱线图_R语言之数
- 下一篇: python基本判断语句_python基