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

Description:

Given a linked list,performs the following task

  1. Remove alternative nodes from second node
  2. Reverse the removed list.
  3. Append the removed list at the end.

Input :

You have to complete the method which takes oneargument: the head ofthe linked list. You should not read any input fromstdin/console.
The struct Node has a data part which stores the data and a nextpointer which points to the next element of the linked list.
There are multiple test cases. For each test case, this method will becalled individually.

Output:

You should not print any output to stdin/console
Example:

Input List: 1->2->3->4->5->6
After step 1 Linked list are 1>3->5 and 2->4->6
After step 2 Linked list are 1->3->5 abd 6->4->2
After step 3 Linked List is1->3->5->6->4->2
Output List: 1->3->5->6->4->2

Note:If you use “Test” or “Expected Output Button” use below example format

Problem Link

/*
  reverse alternate nodes and append at the end
  The input list will have at least one element
  Node is defined as
  struct node
  {
     int data;
     struct node *next;
  }

*/

void rearrange(struct node *odd)
{
    //add code here
    node *tmp=odd;
    node *last,*lastTmp,*prev;
    node *nxt,*alt;
    while(tmp)
    {
        prev=tmp;

        nxt=tmp->next;
        if(nxt==NULL)
        break;
        alt=nxt->next;

        lastTmp=last;
        last=nxt;
        last->next=lastTmp;

        tmp->next=alt;
        tmp=alt;
    }
    node *p,*cur;
    cur=odd;
    while(cur)
    {
        p=cur;
        cur=cur->next;
    }
    p->next=last;
    //prev=last;

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *