天天一道面試題LeetCode 206 -- 反轉鏈表

LeetCode206 反轉鏈表

思路

代碼

#
# @lc app=leetcode.cn id=206 lang=python3
#
# [206] 反轉鏈表
#
# https://leetcode-cn.com/problems/reverse-linked-list/description/
#
# algorithms
# Easy (61.53%)
# Likes:    624
# Dislikes: 0
# Total Accepted:    112.8K
# Total Submissions: 172.9K
# Testcase Example:  '[1,2,3,4,5]'
#
# 反轉一個單鏈表。
# 
# 示例:
# 
# 輸入: 1->2->3->4->5->NULL
# 輸出: 5->4->3->2->1->NULL
# 
# 進階:
# 你能夠迭代或遞歸地反轉鏈表。你可否用兩種方法解決這道題?
# 
#

# @lc code=start
# 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, prev = head, None
        while cur:
            cur.next, prev, cur = prev, cur, cur.next
        return prev
# @lc code=end
相關文章
相關標籤/搜索