# Given a linked list, reverse alternate nodes and append at the end

Given a linked list, reverse alternate nodes and append them to end of list. Extra allowed space is O(1)
Examples

```Input List:  1->2->3->4->5->6
Output List: 1->3->5->6->4->2

Input List:  12->14->16->18->20
Output List: 12->16->20->18->14```

## We strongly recommend that you click here and practice it, before moving on to the solution.

The idea is to maintain two linked lists, one list of all odd positioned nodes (1, 3, 5 in above example) and other list of all even positioned nodes (6, 4 and 2 in above example). Following are detailed steps.
1) Traverse the given linked list which is considered as odd list. Do following for every visited node.
……a) If the node is even node, remove it from odd list and add it to the front of even node list. Nodes are added at front to keep the reverse order.
2) Append the even node list at the end of odd node list.

## C

```#include<stdio.h>
#include<stdlib.h>

/* A linked list node */
struct node
{
int data;
struct node *next;
};

/* Function to reverse all even positioned node and append at the end
void rearrange(struct node *odd)
{
// If linked list has less than 3 nodes, no change is required
if (odd == NULL || odd->next == NULL || odd->next->next == NULL)
return;

// even points to the beginning of even list
struct node *even = odd->next;

// Remove the first even node
odd->next = odd->next->next;

// odd points to next node in odd list
odd = odd->next;

// Set terminator for even list
even->next = NULL;

// Traverse the  list
while (odd && odd->next)
{
// Store the next node in odd list
struct node *temp = odd->next->next;

// Link the next even node at the beginning of even list
odd->next->next = even;
even = odd->next;

// Remove the even node from middle
odd->next = temp;

// Move odd to the next odd node
if (temp != NULL)
odd = temp;
}

// Append the even list at the end of odd list
odd->next = even;
}

/* Function to add a node at the beginning of Linked List */
void push(struct node** head_ref, int new_data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->data  = new_data;
}

/* Function to print nodes in a given linked list */
void printList(struct node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}

/* Druver program to test above function */
int main()
{
struct node *start = NULL;

/* The constructed linked list is:
1->2->3->4->5->6->7 */
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);

printf("\n Linked list before calling  rearrange() ");
printList(start);

rearrange(start);

printf("\n Linked list after calling  rearrange() ");
printList(start);

return 0;
}
```

## Java

```// Java program to reverse alternate nodes of a linked list
// and append at the end

static class Node {

int data;
Node next;

Node(int item) {
data = item;
next = null;
}
}

/* Function to reverse all even positioned node and append at the end
void rearrange(Node odd) {

// If linked list has less than 3 nodes, no change is required
if (odd == null || odd.next == null || odd.next.next == null) {
return;
}

// even points to the beginning of even list
Node even = odd.next;

// Remove the first even node
odd.next = odd.next.next;

// odd points to next node in odd list
odd = odd.next;

// Set terminator for even list
even.next = null;

// Traverse the  list
while (odd != null && odd.next != null) {

// Store the next node in odd list
Node temp = odd.next.next;

// Link the next even node at the beginning of even list
odd.next.next = even;
even = odd.next;

// Remove the even node from middle
odd.next = temp;

// Move odd to the next odd node
if (temp != null) {
odd = temp;
}
}

// Append the even list at the end of odd list
odd.next = even;
}

/* Function to print nodes in a given linked list */
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}

public static void main(String[] args) {

System.out.println("Linked list before calling rearrange : ");

System.out.println("");

System.out.println("Linked list after calling rearrange : ");

}
}

```

## Python

```
# Python program to reverse alternate nodes and append
# at end
# Extra space allowed - O(1)

# Node Class
class Node:

# Constructor to initialize the node object
def  __init__(self, data):
self.data = data
self.next = None

# Linked list class contains node object

def __init__(self):

# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)

def printList(self):
while(temp):
print temp.data,
temp = temp.next

def rearrange(self):

# If linked list has less than 3 nodes, no change
# is required
if (odd is None or odd.next is None or
odd.next.next is None):
return

# Even points to the beginning of even list
even = odd.next

# Remove the first even node
odd.next = odd.next.next

# Odd points to next node in odd list
odd = odd.next

# Set terminator for even list
even.next = None

# Traverse the list
while (odd and odd.next):
# Store the next node in odd list
temp = odd.next.next

# Link the next even node at the beginning
# of even list
odd.next.next = even
even = odd.next

# Remove the even node from middle
odd.next = temp

# Move odd to the next odd node
if temp is not None:
odd = temp

# Append the even list at the end of odd list
odd.next = even

# Code execution starts here
if __name__ == '__main__':

#The constructed linked list is ;
# 1->2->3->4->5->6->7
start.push(7)
start.push(6)
start.push(5)
start.push(4)
start.push(3)
start.push(2)
start.push(1)

print "Linked list before calling  rearrange() "
start.printList()

start.rearrange()

print "\nLinked list after calling  rearrange()"
start.printList()

# This code is contributed by NIkhil Kumar Singh(nickzuck_007)

```

Output:
``` Linked list before calling  rearrange() 1 2 3 4 5 6 7
Linked list after calling  rearrange()  1 3 5 7 6 4 2```

Time Complexity: The above code simply traverses the given linked list. So time complexity is O(n)

Auxiliary Space: O(1)

# Company Wise Coding Practice    Topic Wise Coding Practice

• sangee

What does auxilliary space O(1) mean?

I think this is the exact algorithm what they wanted. I am using O(1) space.
Rather than keeping track of even and odd positions, I used recursion to print the nodes at the even positions in the reverse order.

struct node *temp;
return;
temp->next = NULL;
}

Tell me if this goes wrong some where.

• Kulwinder Kaur

How Auxiliary Space is O(1)?

• SANTOSH KUMAR MISHRA

// I thing very optimize code

{

current1 = current1->next;

while((current1->next) && (current1->next->next))

{

current2->next = current1->next;

current2 = current2->next;

current1->next = current2->next;

current1 = current1->next;

}

if(current1->next)

{

current2->next = current1->next;

current2 = current2->next;

}

if(current2->next) current2->next = NULL;

• samthebest

adding the alternate nodes after tail in insertBefore manner to get reversed nodes
note – it handles the case of min 3 nodes also

{

return;

while(tail->next!=NULL)

{ tail=tail->next;

}

while(ptr1!=tail && ptr2!=tail)

{

ptr1->next=ptr2->next;

ptr2->next=tail->next;

tail->next=ptr2;

ptr1=ptr1->next;

ptr2=ptr1->next;

}

}

• vipinkaushal

much simple code (as i think if any error then please mark it)
thanks ….

#include
using namespace std;
typedef struct list
{
int data;
struct list *next;
} node;
void createlist(node*);
void printlist(node*);
void alterapend(node*);
int main()
{
cout<<endl;
cout<<endl;
return 0;
}
void createlist(node *ptr)
{
int d;
do{
cout<>d;
if(d!=-1)
{
node *ptr2=new node;
ptr2->data=d;
ptr2->next=NULL;
ptr->next=ptr2;
ptr=ptr2;
}
else
break;
}while(1);
return;
}

void printlist(node *ptr)
{
ptr=ptr->next;
while(ptr!=NULL)
{
cout<data<“;
ptr=ptr->next;

}
return;
}
void alterapend(node *ptr)
node *ptr1,*ptr2;
ptr=ptr->next;
while(ptr!=NULL&&ptr->next!=NULL)
{ ptr1=ptr->next;
if(ptr1!=NULL)
{
ptr->next=ptr1->next;
ptr=ptr1->next;

}
}
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
return;
}

• PankajMittalIndia

//Simpler approach simple thinking Not an advanced one
void Algo(struct node *CurrentPtr)

{
bool alt = false;
struct node*AlternateListPtr=0,*pre=0,*tmp;
while(CurrentPtr->next)
{
if(alt == false)
{
pre = CurrentPtr;
alt = true;
CurrentPtr = CurrentPtr->next;
}
else
{
pre->next = CurrentPtr->next ;
tmp = CurrentPtr;
tmp->next = AlternateListPtr;
AlternateListPtr = tmp;
alt = false;
CurrentPtr = pre->next;
}

}
CurrentPtr->next = AlternateListPtr;
}

• Guest

/*Simple Approah than Even/odd code-Mess*/
#include
#include

/* A linked list node */
struct node
{
int data;
struct node *next;
};/* Function to add a node at the beginning of Linked List */
void push(struct node** head_ref, int new_data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
}

/* Function to print nodes in a given linked list */
void printList(struct node *node)
{
while (node != NULL)
{
printf(“%d “, node->data);
node = node->next;
}
}

void rearrange(struct node *CurrentPtr)
{
bool alt = false;
struct node*AlternateListPtr=0,*pre=0,*tmp;
while(CurrentPtr->next)
{
if(alt == false)
{
pre = CurrentPtr;
alt = true;
CurrentPtr = CurrentPtr->next;
}
else
{
pre->next = CurrentPtr->next ;
tmp = CurrentPtr;
tmp->next = AlternateListPtr;
AlternateListPtr = tmp;
alt = false;
CurrentPtr = pre->next;
}

}
CurrentPtr->next = AlternateListPtr;
}
int main()
{

struct node *start = NULL;

/* The constructed linked list is:
1->2->3->4->5->6->7 */
push(&start, 20);
push(&start, 18);
push(&start, 16);
push(&start, 14);
push(&start, 12);
push(&start, 10);

printf(“n Linked list before calling rearrange() “);
printList(start);

rearrange(start);

printf(“n Linked list after calling rearrange() “);
printList(start);

return 0;
}

• Dawn

Implementation in Java

Considering that we have only one list which needs to be rearranged.

1. Find the tail

2. Start from head and check for alternate node (position%2 == 0)

3. If alternate node, move the node after tail and modify the references

4. If not, move to next element.

if(list != null){
Node tempNode = null;
Node prevNode = null;
Node tail = null;
int count = 0;

tail = getTail(list);
while(tempNode != tail){
count++;
if(count%2 == 0){
prevNode.setNext(tempNode.getNext());
tempNode.setNext(tail.getNext());
tail.setNext(tempNode);
tempNode = prevNode.getNext();
}else{
prevNode = tempNode;
tempNode = tempNode.getNext();
}
}
}
}

// Method to find reference to the tail.
Node tail = null;
Node temp = null;
if(list != null){
while(temp != null){
if(temp.getNext() == null){
break;
}else{
temp = temp.getNext();
}
}

tail = temp;
}

return tail;
}

• ALEX

//We can divide a list in two part even and odd pointed by two head,and can add them in last

{

int count=0;

{

count++;

if(count%2==1) //if even node

{

else

{

while(temp->next)

temp=temp->next;

}

}

else

{

{

}

else

{

}

}

}

printf(“nREVERSE DONE…NEW LIST IS :n”);

//display list

}

• Srikar ED

This is more simple, But the list will be traversed approximately 1.5 times… so complexity will be O(n)….

{
struct node *end,*temp,*current;
while(end->next!=NULL)
end=end->next;
temp=current->next;
while(temp!=end && temp!=(end->next))
{
current->next=temp->next;
temp->next=end->next;
end->next=temp;
current=current->next;
temp=current->next;
}
}

• SANTOSH KUMAR MISHRA

//Given a nexted list, reverse alternate nodes and append at the end

//Given a nexted list, reverse alternate nodes and append them to end of list. Extra allowed space is O(1)

#include

#include

struct node

{

int data;

struct node *next;

};

typedef struct node node;

int main(void)

{

int ch,i;

do

{

printf(“nnPress for Insert.”);

printf(“nnPress for Display.”);

printf(“nnPress for Reverse.”);

printf(“nnPress for Reverse Alternate node & Append at the end.”);

printf(“nnPress for Exit.”);

scanf(“n%d”,&ch);

switch(ch)

{

case 1 :

system(“cls”);

printf(“Enter Data to be intert : “);

scanf(“%d”,&i);

break;

case 2 :

system(“cls”);

break;

case 3 :

system(“cls”);

break;

case 4 :

system(“cls”);

break;

}

}while(ch!=0);

return 0;

}

{

node *ptr,*temp;

temp = (node *)malloc(sizeof(node));

temp->data = data;

temp->next = NULL;

{

printf(“nn%d successfully inserted.”,data);

}

while(ptr->next != NULL)

ptr = ptr->next;

ptr->next = temp;

printf(“nn%d successfully inserted.”,data);

}

{

{

printf(“nList is empty.”);

}

if(ptr1->next == NULL)

if(ptr2->next == NULL)

while((ptr2->next != NULL) && (ptr1->next->next->next != NULL))

{

temp = ptr2;

ptr1->next = ptr2->next;

ptr2 = ptr2->next->next;

ptr1 = ptr1->next;

free(temp);

}

if(ptr1->next->next != NULL)

{

temp = ptr2;

ptr1->next = ptr2->next;

ptr2 = ptr2->next->next;

free(temp);

}

if(ptr2 != NULL)

{

temp = ptr2;

ptr1->next = NULL;

free(temp);

}

}

{

prev = NULL;

{

printf(“nnList is Empty.”);

}

while(current != NULL)

{

next = current->next;

current->next = prev;

prev = current;

current = next;

}

//printf(“nnList have been successfully reversed.”);

}

{

{

printf(“nnSorry List is Empty.”);

return;

}

printf(“n”);

while(ptr!=NULL)

{

printf(“%d -> “,ptr->data);

ptr = ptr->next;

}

return;

}

{

printf(“nn————————————————“);

printf(“nnAfter Reversing and appending at the end.nn”);

{

printf(“nList is empty.”);

}

while(ptr->next != NULL)

ptr = ptr->next;

printf(“————————————————nn”);

}

• santosh gupta

void rearrange(struct node *odd)
{

if(odd==NULL||odd->next==NULL||odd->next->next==NULL){

return;
}
struct node *even, *temp,*temp1,*par;
even=odd->next;

odd->next=odd->next->next;
odd=odd->next;

even->next=NULL;

while(odd&&odd->next){
temp1=odd->next->next;

temp=odd->next;
temp->next=even;
even=temp;

odd->next=temp1;
par=odd;
odd=odd->next;
}

if(odd==NULL){
par->next=even;
}
else
odd->next=even;
}

• Ankit Jain

#include
#include
struct Node
{
int data;
struct Node *next;
};

{
if(temp==NULL)
{
temp=(struct Node*)malloc(sizeof(struct Node));
temp->data=data;
temp->next=NULL;
return temp;
}
else
{
while(temp->next!=NULL)
temp=temp->next;

temp->next=(struct Node*)malloc(sizeof(struct Node));
temp->next->data=data;
temp->next->next=NULL;
}
}

{
{
}

}

struct Node * reverse(struct Node *head)
{
int i=1;
{
{
}
}
return temp1;
}

main()
{
int a[]={12,14,16,18,20},i;
for(i=0;i<5;i++)
return 0;
}

• chandan

Can anyone explain me how auxillary space is o(1)

• Stack oddNodes = new Stack(null);
while(current.getNext()!=null){
oddNodes.push(current.getNext());
current.setNext(current.getNext().getNext());
if(current.getNext()!=null)
current = current.getNext();
}
while(oddNodes.getTop()!=null){
current.setNext(oddNodes.pop());
current = current.getNext();
}
return LL;

• Guest

evenodd pos

• Sumitgolusagar

node *alt_node_reverse(node *p){
temp=NULL;
while(p && p->next){
q=p->next;
if(q->next!=NULL){
p->next=q->next;
p=p->next;
}
else
p->next=NULL;
q->next=temp;
temp=q;
}
p->next=temp;
}

• xxx

this solution is wrong

• Aniruddha

I found the solution very easy to understand and implement. I, like many others, followed the in-place approach to just pluck the nodes at even positions and add them after the last node in the original list.

{
unsigned int listSize = 11;

cout << "Printing … ";
list.Print();

const unsigned int length = list.Length();
if (length 1 -> 2 -> 3 -> 4 -> 5
// 0 -> 2 -> 4 -> 5 -> 3 -> 1

// Odd number of nodes
// 0 -> 1 -> 2 -> 3 -> 4
// 0 -> 2 -> 4 -> 3 -> 1

// Find the last node in list
while (originalLastNode->Next != NULL)
{
originalLastNode = originalLastNode->Next;
}

// Start from the head, for even node at an even position,
// disengage the next node and add it at the end while updating
// the lastNode variable
unsigned int position = 0;

while (current != originalLastNode && current->Next != originalLastNode)
{
Node* temp = current->Next;

// Move current->next node after the last node
current->Next = current->Next->Next;
temp->Next = originalLastNode->Next;
originalLastNode->Next = temp;

// Move to next node (originally) at an even position
current = current->Next;
}

cout << "Printing after modification … ";
list.Print();
}

• Aman Agarwal

struct node{
int data;
struct node *next;
}*ptr,*start,*newnode;

void appendodd()
{
int c=1;//counter to find even or odd no of item
ptr=start;
struct node *last,*first,*prev;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
last=ptr; //last point to the last element of the original linklist
ptr=start;
while(ptr!=last)
{
if(c%2==1)//if odd
{
prev=ptr;
ptr=ptr->next;
c++;
}
else
{
prev->next=ptr->next;
if(c==2) // for node number 2
{
first=ptr; // initialise *first with the node no 2 of the list
first->next=NULL;
}
else
{
ptr->next=first;
first=ptr;

}
c++;
ptr=prev->next;
}
}
ptr->next=first;
}

• RGuest

struct node
{
int data;
struct node *next;
};

/* Function to insert a node at the beginning */
void push(struct node ** head_ref, int new_data)
{
/* allocate node */
struct node* new_node = (struct node*) malloc(sizeof(struct node));

/* put in the data */
new_node->data = new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

/* Function to print linked list */
{
while (temp != NULL)
{
printf(“%d “, temp->data);
temp = temp->next;
}
printf(“n”);
}

void push1(struct node ** head_ref, struct node *new_node)
{
/* link the old list off the new node */

/* move the head to point to the new node */
}
// Function to skip M nodes and then delete N nodes of the linked list.
void rearrange(struct node *head, int M, int N)
{
struct node *curr = head, *t;
int count;

struct node *result = NULL;
// The main loop that traverses through the whole list
while (curr)
{
// Skip M nodes
for (count = 1; countnext;

// If we reached end of list, then return
if (curr == NULL)
{
return;
}
// Start from next node and delete N nodes
t = curr->next;
for (count = 1; countnext;
push1(&result,temp);
}

if(t ==NULL)
{
curr->next = result;
break;
}
// Link the previous list with remaining nodes
curr->next = t;
// Set current pointer for next iteration
curr = t;
}
}

// Driver program to test above functions
int main()
{
1->2->3->4->5->6->7->8->9->10 */
int M=1, N=1;

printf(“M = %d, N = %d nGiven Linked list is :n”, M, N);

printf(“nLinked list after Rearrange is :n”);

return 0;
}

• RGuest

void push1(struct node ** head_ref, struct node *new_node)
{
/* link the old list off the new node */

/* move the head to point to the new node */
}
// Function to skip M nodes and then delete N nodes of the linked list.
void rearrange(struct node *head, int M, int N)
{
struct node *curr = head, *t;
int count;

struct node *result = NULL;
// The main loop that traverses through the whole list
while (curr)
{
// Skip M nodes
for (count = 1; countnext;

// If we reached end of list, then return
if (curr == NULL)
{
return;
}
// Start from next node and delete N nodes
t = curr->next;
for (count = 1; countnext;
push1(&result,temp);
}

// Link the previous list with remaining nodes
if(t ==NULL)
{
curr->next = result;
break;
}

curr->next = t;
// Set current pointer for next iteration
curr = t;

}
}

• ajay

{
struct node* temp = NULL;

{
pre->next = temp;
temp = pre;
}

}

• Sudhanshu

I used a rather simple approach to this problem. no even or odd ..

• Sudhanshu

void reArrange(struct node* start)

{

struct node* a,*r,*i,*s,*x;

for(i=start;i->next!=NULL ;i=i->next);

a=i;

for(i=start;i!=a && i->next!=a;i=i->next){

r=i->next;

s=r->next;

i->next=s;

x=a->next;

a->next=r;

r->next=x;

}

}

• hxgxs1

http://ideone.com/T4Bu2X

Traverse the list pluck out the even nodes and insert them at the last node’s next node.
e.g
input:: 1 2 3 4 5 6
after 1st loop execution : 1 3 4 5 6 2
after 2nd loop execution : 1 3 5 6 4 2
That’s it.

• suresh kumar mahawar

can it implement recursively?

• saurabh

Why not just traverse, and unlink and insert the even nodes after the original tailnode (called oldtail in the program). Here are the relevant functions:

• saurabh

void list::revappend()//public calling function
{
oldtail=tail;
return;
}

void list::walkthrough(Node* r)//private recursive function to walkthrough
{
if(r==NULL)
return;
if(r==oldtail ||r->next==oldtail)
return;
Node* nextnode=r->next;
if(r->next)
r->next=r->next->next;
insert_after(nextnode);
walkthrough(r->next);
return;
}

void list::insert_after(Node*& r)//private function to insert after tailnode

{
if(r==NULL || oldtail==NULL)
return;
if(r==oldtail)
return;
Node* nextnode=oldtail->next;
if(nextnode==NULL)
tail=r;
oldtail->next=r;
r->next=nextnode;
return;
}

void ReverseAltNode(Node* pIn)

{

Node* pTempNodeList = NULL;

if(pIn == NULL)

return;

bool isAlternate = false;

Node* nodeItr = pIn;

while(nodeItr && nodeItr->next)

{

if(isAlternate)

{

nodeItr = nodeItr->next;

isAlternate = false;

}

else

{

isAlternate = true;

Node* temp = nodeItr->next;

nodeItr->next = temp->next;

temp->next = pTempNodeList;

pTempNodeList = temp;

}

};

nodeItr->next = pTempNodeList;

}

• geekykid

shouldn’t output be 1 3 5 7 6 4 2 instead of 1 4 6 7 5 3 2

• geekykid

there is flaw in the code. ‘odd’ pointer is not changed before entering the while loop.

• GeeksforGeeks

Thanks for pointing this out. We have fixed the problem.

• GeeksforGeeks

We have fixed the code.

if (curr==null || curr.next==null || curr.next.next==null) return head;
Node prevOdd = null;
Node prevEven = null;
boolean operation=true;
Node tmp;
while (curr!=null){
if (operation==true){
tmp = curr.next;
if (curr.next!=null)
curr.next = curr.next.next;
prevEven = curr;
curr = tmp;
}
else{
tmp = curr.next;
curr.next = prevOdd;
prevOdd = curr;
curr = tmp;
}
operation = !operation;
}

prevEven.next = prevOdd;
}

Time complexity is O(N)

• nani

the output should be Linked list before calling rearrange() 1 2 3 4 5 6 7
Linked list after calling rearrange() 1 4 6 7 5 3 2::

1 3 5 7 6 4 2 … instead of 14 6 7 5 3 2