反转链表

C++

#include <iostream>

using namespace std;

class Node {
public:
    int value;
    Node *next;

    Node(int value) {
        this->value = value;
        this->next = nullptr;
    }
};

Node *reverse(Node *head) {
    Node *prev = nullptr, *next;
    while (head) {
        next = head->next;
        head->next = prev;
        prev = head;
        head = next;
    }
    return prev;
}

Node *reverse_recursive(Node *head) {
    if (!head || !head->next)
        return head;
    Node *ret = reverse_recursive(head->next);
    head->next->next = head;
    head->next = nullptr;
    return ret;
}

int main() {
    Node *head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);

    head = reverse(head);

    while (head) {
        cout << head->value << endl;
        head = head->next;
    }

    return 0;
}

Python

# 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:
        prev = None
        while head:
            head.next, prev, head = prev, head, head.next
        return prev