Tuesday, February 22, 2022

LeetCode 206. Reverse Linked List

https://leetcode.com/problems/reverse-linked-list/ Problem
Solution
/**
* 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* recursive(ListNode* cur, ListNode* prev){
if(!cur) return prev;
auto tmp = cur->next;
cur->next = prev;
return recursive(tmp, cur);
}
ListNode* reverseList(ListNode* head) {
// new tail pointer
ListNode* prev = NULL;
// iterative pointer
ListNode* cur = head;
// iterative
// while (cur) {
// auto n = cur->next;
// cur->next = prev;
// prev = cur;
// cur = n;
// }
// return prev
// recursive
return recursive(cur, prev);
}
};

No comments:

Post a Comment