Rearrange a Linked List in Zig-Zag fashion | Set-2
Given a linked list, rearrange it such that converted list should be of the form a < b > c < d > e < f .. where a, b, c.. are consecutive data node of linked list. Note that it is not allowed to swap data.
Examples:
Input: 1->2->3->4 Output: 1->3->2->4 Input: 11->15->20->5->10 Output: 11->20->5->15->10
Approach:
A solution that converts given list into zigzag form is discussed in previous post. The solution discussed performs conversion by swapping data of nodes. Swapping data of nodes may be expensive in many situations when the data contains many fields. In this post, a solution that performs conversion by swapping links is discussed.
The idea is to traverse the given linked list and check if current node maintains the zigzag order or not. To check if given node maintains zigzag order or not, a variable ind is used. If ind = 0, then the current node’s data should be less than its adjacent node’s data and if ind = 1, then current node’s data should be greater than its adjacent node’s data. If the current node violates the zigzag order, then swap the position of both nodes. For doing this step, maintain two pointers prev and next. prev stores previous node of current node and next stores new next node of current node. To swap both nodes, the following steps are performed:
- Make next node of current node, the next node of previous node.
- Make the current node next node of its adjacent node.
- Make current node next = next node.
Below is the implementation of above approach:
C++
// CPP program to arrange linked list in // zigzag fashion #include <bits/stdc++.h> using namespace std; /* Link list Node */struct Node { int data; struct Node* next; }; // This function converts the Linked list in // zigzag fashion Node* zigZagList(Node* head) { if (head == NULL || head->next == NULL) { return head; } // to store new head Node* res = NULL; // to traverse linked list Node* curr = head; // to store previous node of current node Node* prev = NULL; // to store new next node of current node Node* next; // to check if current element should // be less than or greater than. // ind = 0 --> less than // ind = 1 --> greater than int ind = 0; while (curr->next) { // If elements are not in zigzag fashion // swap them. if ((ind == 0 && curr->data > curr->next->data) || (ind == 1 && curr->data < curr->next->data)) { if (res == NULL) res = curr->next; // Store new next element of current // node next = curr->next->next; // Previous node of current node will // now point to next node of current node if (prev) prev->next = curr->next; // Change next pointers of both // adjacent nodes curr->next->next = curr; curr->next = next; // Change previous pointer. if (prev) prev = prev->next; else prev = res; } // If already in zig zag form, then move // to next element. else { if (res == NULL) { res = curr; } prev = curr; curr = curr->next; } // Update info whether next element should // be less than or greater than. ind = 1 - ind; } return res; } /* UTILITY FUNCTIONS *//* Function to push a Node */void push(Node** head_ref, int new_data) { /* allocate Node */ struct Node* new_Node = new 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* Node) { while (Node != NULL) { printf("%d->", Node->data); Node = Node->next; } } /* Driver program to test above function*/int main(void) { /* Start with the empty list */ struct Node* head = NULL; // create a list 4 -> 3 -> 7 -> 8 -> 6 -> 2 -> 1 // answer should be -> 3 7 4 8 2 6 1 push(&head;, 1); push(&head;, 2); push(&head;, 6); push(&head;, 8); push(&head;, 7); push(&head;, 3); push(&head;, 4); printf("Given linked list \n"); printList(head); head = zigZagList(head); printf("\nZig Zag Linked list \n"); printList(head); return 0; } |
Java
// Java program to arrange linked list in // zigzag fashion class GFG { /* Link list Node */static class Node { int data; Node next; }; static Node head; // This function converts the Linked list in // zigzag fashion static Node zigZagList(Node head) { if (head == null || head.next == null) { return head; } // to store new head Node res = null; // to traverse linked list Node curr = head; // to store previous node of current node Node prev = null; // to store new next node of current node Node next; // to check if current element should // be less than or greater than. // ind = 0 -. less than // ind = 1 -. greater than int ind = 0; while (curr.next != null) { // If elements are not in zigzag fashion // swap them. if ((ind == 0 && curr.data > curr.next.data) || (ind == 1 && curr.data < curr.next.data)) { if (res == null) res = curr.next; // Store new next element of current // node next = curr.next.next; // Previous node of current node will // now point to next node of current node if (prev != null) prev.next = curr.next; // Change next pointers of both // adjacent nodes curr.next.next = curr; curr.next = next; // Change previous pointer. if (prev != null) prev = prev.next; else prev = res; } // If already in zig zag form, then move // to next element. else { if (res == null) { res = curr; } prev = curr; curr = curr.next; } // Update info whether next element should // be less than or greater than. ind = 1 - ind; } return res; } /* UTILITY FUNCTIONS *//* Function to push a Node */static void push(Node head_ref, int new_data) { /* allocate Node */ Node new_Node = new 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; head = head_ref; } /* Function to print linked list */static void printList(Node Node) { while (Node != null) { System.out.printf("%d->", Node.data); Node = Node.next; } } // Driver Code public static void main(String[] args) { /* Start with the empty list */ head = null; // create a list 4 -> 3 -> 7 -> 8 -> 6 -> 2 -> 1 // answer should be -> 3 7 4 8 2 6 1 push(head, 1); push(head, 2); push(head, 6); push(head, 8); push(head, 7); push(head, 3); push(head, 4); System.out.printf("Given linked list \n"); printList(head); head = zigZagList(head); System.out.printf("\nZig Zag Linked list \n"); printList(head); } } // This code is contributed by Rajput-Ji |
Python3
# Python3 program to arrange # linked list in zigzag fashion class Node: def __init__(self, data): self.data = data self.next = None # This function converts the # Linked list in zigzag fashion def zigZagList(head): if head == None or head.next == None: return head # To store new head res = None # To traverse linked list curr = head # To store previous node of current node prev = None # to check if current element should # be less than or greater than. # ind = 0 -. less than # ind = 1 -. greater than ind = 0 while curr.next: # If elements are not in # zigzag fashion swap them. if ((ind == 0 and curr.data > curr.next.data) or (ind == 1 and curr.data < curr.next.data)): if res == None: res = curr.next # Store new next element of current # node next = curr.next.next # Previous node of current node will # now point to next node of current node if prev: prev.next = curr.next # Change next pointers of # both adjacent nodes curr.next.next = curr curr.next = next # Change previous pointer. if prev: prev = prev.next else: prev = res # If already in zig zag form, # then move to next element. else: if res == None: res = curr prev = curr curr = curr.next # Update info whether next element # should be less than or greater than. ind = 1 - ind return res # UTILITY FUNCTIONS # Function to push a Node def push(head_ref, new_data): # put in the data new_Node = Node(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 return head_ref # Function to print linked list def printList(Node): while Node != None: print(Node.data, end = "->") Node = Node.next # Driver program to test above function if __name__ == "__main__": # Start with the empty list head = None # create a list 4 . 3 . 7 . 8 . 6 . 2 . 1 # answer should be . 3 7 4 8 2 6 1 head = push(head, 1) head = push(head, 2) head = push(head, 6) head = push(head, 8) head = push(head, 7) head = push(head, 3) head = push(head, 4) print("Given linked list") printList(head) head = zigZagList(head) print("\nZig Zag Linked list") printList(head) # This code is contributed by Rituraj Jain |
C#
// C# program to arrange linked list in // zigzag fashion using System; class GFG { /* Link list Node */public class Node { public int data; public Node next; }; static Node head; // This function converts the Linked list in // zigzag fashion static Node zigZagList(Node head) { if (head == null || head.next == null) { return head; } // to store new head Node res = null; // to traverse linked list Node curr = head; // to store previous node of current node Node prev = null; // to store new next node of current node Node next; // to check if current element should // be less than or greater than. // ind = 0 -. less than // ind = 1 -. greater than int ind = 0; while (curr.next != null) { // If elements are not in zigzag fashion // swap them. if ((ind == 0 && curr.data > curr.next.data) || (ind == 1 && curr.data < curr.next.data)) { if (res == null) res = curr.next; // Store new next element of current // node next = curr.next.next; // Previous node of current node will // now point to next node of current node if (prev != null) prev.next = curr.next; // Change next pointers of both // adjacent nodes curr.next.next = curr; curr.next = next; // Change previous pointer. if (prev != null) prev = prev.next; else prev = res; } // If already in zig zag form, then move // to next element. else { if (res == null) { res = curr; } prev = curr; curr = curr.next; } // Update info whether next element should // be less than or greater than. ind = 1 - ind; } return res; } /* UTILITY FUNCTIONS *//* Function to push a Node */static void push(Node head_ref, int new_data) { /* allocate Node */ Node new_Node = new 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; head = head_ref; } /* Function to print linked list */static void printList(Node Node) { while (Node != null) { Console.Write("{0}->", Node.data); Node = Node.next; } } // Driver Code public static void Main(String[] args) { /* Start with the empty list */ head = null; // create a list 4 -> 3 -> 7 -> 8 -> 6 -> 2 -> 1 // answer should be -> 3 7 4 8 2 6 1 push(head, 1); push(head, 2); push(head, 6); push(head, 8); push(head, 7); push(head, 3); push(head, 4); Console.Write("Given linked list \n"); printList(head); head = zigZagList(head); Console.Write("\nZig Zag Linked list \n"); printList(head); } } // This code is contributed by 29AjayKumar |
Given linked list 4->3->7->8->6->2->1-> Zig Zag Linked list 3->7->4->8->2->6->1->
Time Complexity: O(N)
Auxiliary Space: O(1)
Recommended Posts:
- Rearrange a Linked List in Zig-Zag fashion
- Rearrange a given linked list in-place.
- Rearrange a linked list in to alternate first and last element
- Rearrange a linked list such that all even and odd positioned nodes are together
- Create new linked list from two given linked list with greater element at each node
- Merge a linked list into another linked list at alternate positions
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Modify and Rearrange List
- Check if a linked list is Circular Linked List
- Convert Singly Linked List to XOR Linked List
- Rearrange a given list such that it consists of alternating minimum maximum elements
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



