less than 1 minute read

Given a singly linked list node, return its reverse.

Bonus: Can you do this in O(1) space?

Constraints

  • n ≤ 100,000 where n is the number of nodes in node

https://binarysearch.com/problems/Reverse-a-Linked-List

ExamplesPermalink

Example 1Permalink

Input

  • node =
example1Node 0 1 1 2 0->1 2 3 1->2 3 4 2->3

Output

  • answer =
example1Output 0 4 1 3 0->1 2 2 1->2 3 1 2->3

Example 2Permalink

Input

  • node =
example2Node 0 0 1 1 0->1

Output

  • answer =
example2Output 0 1 1 0 0->1

SolutionPermalink

/**
* class LLNode {
* public:
* int val;
* LLNode *next;
* };
*/
LLNode* solve(LLNode* node) {
LLNode* prev = NULL;
while (node) {
LLNode* tmp = node->next;
node->next = prev;
prev = node;
node = tmp;
}
return prev;
}

Leave a comment