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 to minimize the browser and try this yourself first.

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.

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

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





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

  • http://www.harshssd.appspot.com/ Harsha

    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