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
   odd is the head node of given linked list */
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;
    new_node->next = (*head_ref);
    (*head_ref)    = new_node;
}

/* 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

class LinkedList {

    static Node head;

    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
     odd is the head node of given linked list */
    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) {
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(2);
        list.head.next.next = new Node(3);
        list.head.next.next.next = new Node(4);
        list.head.next.next.next.next = new Node(5);
        list.head.next.next.next.next.next = new Node(6);
        list.head.next.next.next.next.next.next = new Node(7);

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

        System.out.println("");
        list.rearrange(head);

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

    }
}

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
class LinkedList:
    
    # Constructor to initialize head
    def __init__(self):
        self.head = None

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

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

    def rearrange(self):
        
        # If linked list has less than 3 nodes, no change
        # is required 
        odd = self.head
        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__':
    start = LinkedList()
    
    #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)

This article is contributed by Aman Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above









Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the link here.

  • 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;

    node *Insert(node *head,int data);

    void Display(node *head);

    node *Reverse(node *head);

    node *ReverseAltApp(node *head);

    node *AppendList(node *head1,node *head2);

    int main(void)

    {

    node *head = NULL;

    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.”);

    printf(“nnEnter your choice : “);

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

    switch(ch)

    {

    case 1 :

    system(“cls”);

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

    scanf(“%d”,&i);

    head = Insert(head,i);

    Display(head);

    break;

    case 2 :

    system(“cls”);

    Display(head);

    break;

    case 3 :

    system(“cls”);

    head = Reverse(head);

    Display(head);

    break;

    case 4 :

    system(“cls”);

    head = ReverseAltApp(head);

    Display(head);

    break;

    }

    }while(ch!=0);

    return 0;

    }

    node *Insert(node *head,int data)

    {

    node *ptr,*temp;

    ptr = head;

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

    temp->data = data;

    temp->next = NULL;

    if(head == NULL)

    {

    head = temp;

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

    return head;

    }

    while(ptr->next != NULL)

    ptr = ptr->next;

    ptr->next = temp;

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

    return head;

    }

    node *ReverseAltApp(node *head)

    {

    node *head2,*temp,*ptr1,*ptr2;

    head2 = NULL;

    ptr1 = head;

    ptr2 = head->next;

    if(head == NULL)

    {

    printf(“nList is empty.”);

    return head;

    }

    if(ptr1->next == NULL)

    return head;

    if(ptr2->next == NULL)

    return head;

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

    {

    temp = ptr2;

    head2 = Insert(head2,ptr2->data);

    ptr1->next = ptr2->next;

    ptr2 = ptr2->next->next;

    ptr1 = ptr1->next;

    free(temp);

    }

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

    {

    temp = ptr2;

    head2 = Insert(head2,ptr2->data);

    ptr1->next = ptr2->next;

    ptr2 = ptr2->next->next;

    free(temp);

    }

    if(ptr2 != NULL)

    {

    temp = ptr2;

    head2 = Insert(head2,ptr2->data);

    ptr1->next = NULL;

    free(temp);

    }

    head = AppendList(head,head2);

    return head;

    }

    node *Reverse(node *head)

    {

    node *prev,*next,*current = head;

    prev = NULL;

    if(head == NULL)

    {

    printf(“nnList is Empty.”);

    return head;

    }

    while(current != NULL)

    {

    next = current->next;

    current->next = prev;

    prev = current;

    current = next;

    }

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

    head = prev;

    return head;

    }

    void Display(node *head)

    {

    node *ptr = head;

    if(head == NULL)

    {

    printf(“nnSorry List is Empty.”);

    return;

    }

    printf(“n”);

    while(ptr!=NULL)

    {

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

    ptr = ptr->next;

    }

    return;

    }

    node *AppendList(node *head1,node *head2)

    {

    node *ptr = head1;

    head2 = Reverse(head2);

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

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

    if(head1 == NULL)

    {

    printf(“nList is empty.”);

    return head1;

    }

    while(ptr->next != NULL)

    ptr = ptr->next;

    ptr->next = head2;

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

    return head1;

    }

  • 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;
    };

    struct Node * insertLinked(struct Node *head,int data)
    {
    struct Node *temp=head;
    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;
    return head;
    }
    }

    void traverse(struct Node *head)
    {
    while(head)
    {
    printf(“%d “,head->data);
    head=head->next;
    }

    }

    struct Node * reverse(struct Node *head)
    {
    int i=1;
    struct Node*head2=NULL,*t,*temp,*temp1=head;
    while(head)
    {
    if(head->next)
    {
    t=head->next->next;
    head->next->next=head2;
    head2=head->next;
    head->next=t;
    }
    temp=head;
    head=head->next;
    }
    temp->next=head2;
    return temp1;
    }

    main()
    {
    struct Node *head=NULL;
    int a[]={12,14,16,18,20},i;
    for(i=0;i<5;i++)
    head=insertLinked(head,a[i]);
    head=reverse(head);
    traverse(head);
    return 0;
    }

  • chandan

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

  • Stack oddNodes = new Stack(null);
    LocalLinkedList.Node current = LL.getHead();
    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){
    node *head,*q,*temp;
    head=q=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;
    return head;
    }

    • 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.

    void LinkedListProblems::ReverseAlternateNodesAndAppendAtTheEnd()
    {
    LinkedList list;
    unsigned int listSize = 11;

    LinkedList::Populate(list, listSize);
    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
    Node* originalLastNode = list.Head();
    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;
    Node* current = list.Head();

    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

    // A linked list node
    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 */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref) = new_node;
    }

    /* Function to print linked list */
    void printList(struct node *head)
    {
    struct node *temp = head;
    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 */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref) = 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()
    {
    /* Create following linked list
    1->2->3->4->5->6->7->8->9->10 */
    struct node* head = NULL;
    int M=1, N=1;
    push(&head, 10);
    push(&head, 9);
    push(&head, 8);
    push(&head, 7);
    push(&head, 6);
    push(&head, 5);
    push(&head, 4);
    push(&head, 3);
    push(&head, 2);
    push(&head, 1);

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

    rearrange(head, M, N);

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

    return 0;
    }

  • RGuest

    void push1(struct node ** head_ref, struct node *new_node)
    {
    /* link the old list off the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref) = 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

    void rearrange(struct node* head)
    {
    struct node* temp = NULL;

    while(head and head->next)
    {
    struct node* pre = head->next;
    head->next = head->next->next;
    if(head->next)
    head = head->next;
    pre->next = temp;
    temp = pre;
    }
    head->next = temp;

    }

  • 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;
      walkthrough(head);
      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;
      }

  • Karthikeyan Mahadevan

    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.
      please check

      • GeeksforGeeks

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

    • GeeksforGeeks

      We have fixed the code.

  • Aditya

    public Node reverseInAlternate(Node head){
    Node curr = head;
    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;
    return head;
    }

    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

      • Aditya

        Is the code above giving 1 4 6 7 5 3 2?

        • Aditya

          I tested my code and it gives 1 3 5 7 6 4 2 for the input 1 2 3 4 5 6 7