# Rearrange a linked list in Zig-Zag

## Rearrange a given linked list such that it should be in form a < b > c < d > e < f > for linked list with a, b, c, d, e, f as nodes.

### Example Time complexity : O(n)

## Algorithm

b. Create a variable flag (Boolean value).

1. If flag is true then the next node of current should be greater. If not swap them.

2. If flag is false then the next node of current should be smaller. If not swap them.

c. While traversing, change the value of flag every time we move one position ahead.

d. The final list is the desired list.

## Algorithm working  ## C++ Program

```#include <bits/stdc++.h>

using namespace std;

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

/* Function to insertAtBeginning a node */
void insertAtBeginning(struct LLNode** head, int dataToBeInserted)
{
struct LLNode* curr = new LLNode;
curr->data = dataToBeInserted;
curr->next = NULL;
*head=curr; //if this is first node make this as head of list

else
{
curr->next=*head; //else make the curr (new) node's next point to head and make this new node a the head
}

//O(1) constant time
}

void display(struct LLNode**node)
{
struct LLNode *temp= *node;
while(temp!=NULL)
{
if(temp->next!=NULL)
cout<<temp->data<<"->";
else
cout<<temp->data;

temp=temp->next; //move to next node
}
//O(number of nodes)
cout<<endl;
}

{
bool flag = true;

while (curr->next != NULL)
{
//Condition is X > Y > Z swap Y and Z
//convert to X > Z < Y or Z < Y with no X
if(flag)
{
if (curr->data > curr->next->data)
{
swap(curr->data, curr->next->data);
}
}
//Condition is X < Y < Z swap Y and Z
//convert to X < Z > Y or Z > Y with no X
else
{
if (curr->data < curr->next->data)
{
swap(curr->data, curr->next->data);
}
}
//Move forward by reversing flag
curr = curr->next;
flag = !flag;
}
//O(number of nodes)
}

//Main function
int main(void)
{