206. Reverse Linked List

https://leetcode.com/problems/reverse-linked-list

Problem

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

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

Solution

1. Recursive

/**
 * 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* reverseList(ListNode* head) {
        if (head == nullptr) return head;
        auto *temp = head->next;
        head->next = nullptr;
        return reverseList(head, temp);
    }
    ListNode* reverseList(ListNode* current, ListNode* next) {
        if (next == nullptr) return current;
        auto *new_next = next->next;
        next->next = current;
        return reverseList(next, new_next);
    }
};

2. Iterative

  • #linkedlist

Last updated

Was this helpful?