Search⌘ K
AI Features

Reverse Even Nodes in a Linked List

Explore how to reverse the nodes at even positions in a singly linked list without extra memory allocation. Understand the process of separating even and odd nodes, reversing the even nodes by pushing them to a new list's head, and merging them back alternately. This lesson guides you to implement an efficient O(n) time and space solution, enhancing your linked list manipulation skills for coding interviews.

Statement

Given a singly linked list, reverse the nodes at even positions and return the linked list.

Example

Let’s take the below linked list as an example:

g head1 head a 7 head1->a NULL NULL b 14 a->b c 21 b->c d 28 c->d e 9 d->e e->NULL

After reversing the nodes at even positions, it should look like this:

g head1 head a 7 head1->a NULL NULL d 28 a->d b 14 e 9 b->e c 21 c->b d->c e->NULL

Sample input

[7, 14, 21, 28, 9]

Expected output

[7, 28, 21, 14, 9]

Try it yourself

Files
main.cpp
LinkedList.cpp
LinkedListNode.cpp
#include <vector>
#include "LinkedList.cpp"
using namespace std;
typedef LinkedListNode* NodePtr;
NodePtr ReverseEvenNodes(NodePtr head) {
//TODO: Write - Your - Code
return head;
}
...