鱼C论坛

 找回密码
 立即注册
查看: 873|回复: 0

[技术交流] 【朱迪的LeetCode刷题笔记】】206. Reverse Linked List #Easy #Python #C++

[复制链接]
发表于 2023-5-30 09:23:52 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Judie 于 2023-5-29 21:03 编辑

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:
Input: head = [1,2]
Output: [2,1]

Example 3:
Input: head = []
Output: []


Constraints:
The number of nodes in the list is the range [0, 5000].
-5000 <= Node.val <= 5000

Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?


Judy
Python iterative version
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev = None
        curr = head
        while curr:
            temp = curr.next
            curr.next = prev
            prev = curr
            curr = temp
        return prev

https://leetcode.com/problems/re ... 3/python-recursive/
Solution 1
Python recursive version
class Solution:
    def reverseList(self, head: Optional[ListNode], prev = None) -> Optional[ListNode]:
        if head is None:
            return prev
        next = head.next
        head.next = prev
        return self.reverseList(next, head)
        ```

Mike
C++ iterative version
ListNode* reverseList(ListNode* head) {
        ListNode* current = head;
        ListNode* prev = nullptr;
        while (current != nullptr) {
            ListNode* temp = current->next;
            current->next = prev;
            prev = current;
            current = temp;
        }
        return prev;
    }
C++ recursive version
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseLast(ListNode* head, ListNode* prev) {
        if (head->next == nullptr) {
            head->next = prev;
            return head;
        }
        ListNode* retval = reverseLast(head->next, head);
        head->next = prev;
        return retval;
    }
    ListNode* reverseList(ListNode* head) {
        if (head == nullptr) {
            return head;
        }
        return reverseLast(head, nullptr);
    }
};

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-18 05:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表