Open In App

Python Program For Rearranging A Linked List In Zig-Zag Fashion

Last Updated : 09 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a linked list, rearrange it such that the converted list should be of the form a < b > c < d > e < f … where a, b, c… are consecutive data nodes of the linked list.

Examples: 

Input:  1->2->3->4
Output: 1->3->2->4 
Explanation: 1 and 3 should come first before 2 and 4 in
             zig-zag fashion, So resultant linked-list 
             will be 1->3->2->4. 

Input:  11->15->20->5->10
Output: 11->20->5->15->10 

We strongly recommend that you click here and practice it, before moving on to the solution.

A simple approach to do this is to sort the linked list using merge sort and then swap alternate, but that requires O(n Log n) time complexity. Here n is a number of elements in the linked list.

An efficient approach that requires O(n) time is, using a single scan similar to bubble sort and then maintain a flag for representing which order () currently we are. If the current two elements are not in that order then swap those elements otherwise not. Please refer to this for a detailed explanation of the swapping order. 

follow” href=”https://www.geeksforgeeks.org/converting-an-array-of-integers-into-zig-zag-fashion/”>this for a detailed explanation of the swapping order. 

Python




# Python code to rearrange linked list 
# in zig zag fashion
  
# Node class 
class Node: 
  
    # Constructor to initialize 
    # the node object 
    def __init__(self, data): 
        self.data = data 
        self.next = None
  
  
# This function distributes the Node 
# in zigzag fashion
def zigZagList(head):
  
    # If flag is true, then next node 
    # should be greater in the desired 
    # output.
    flag = True
  
    # Traverse linked list starting 
    # from head.
    current = head
    while (current.next != None):
      
        # "<" relation expected
        if (flag): 
          
            # If we have a situation like 
            # A > B > C where A, B and C 
            # are consecutive Nodes in list
            # we get A > B < C by swapping B
            # and C 
            if (current.data > 
                current.next.data):
                t = current.data
                current.data = current.next.data
                current.next.data = t
              
        # ">" relation expected
        else :
          
            # If we have a situation like 
            # A < B < C where A, B and C 
            # are consecutive Nodes in list we
            # get A < C > B by swapping B and C 
            if (current.data < 
                current.next.data):
                t = current.data
                current.data = current.next.data
                current.next.data = t
              
        current = current.next
        if(flag):
  
            # flip flag for reverse checking 
            flag = False 
        else:
            flag = True
    return head
  
# Function to insert a Node in 
# the linked list at the beginning.
def push(head, k):
  
    tem = Node(0)
    tem.data = k
    tem.next = head
    head = tem
    return head
  
# Function to display Node of 
# linked list.
def display(head):
    curr = head
    while (curr != None): 
        print(curr.data, 
              "->", end =" ")
        curr = curr.next
      
    print("None")
  
# Driver code
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 ")
display(head)
  
head = zigZagList(head)
  
print("Zig Zag Linked list ")
display(head)
# This code is contributed by Arnab Kundu


Output:

Given linked list 
4->3->7->8->6->2->1->NULL
Zig Zag Linked list 
3->7->4->8->2->6->1->NULL

Time Complexity: O(N), as we are using a loop for traversing the linked list.

Auxiliary Space: O(1), as we are not using extra space.

Another Approach:
In the above code, the push function pushes the node at the front of the linked list, the code can be easily modified for pushing the node at the end of the list. Another thing to note is, swapping of data between two nodes is done by swap by value not swap by links for simplicity, for the swap by links technique please see this.

This can be also be done recursively. The idea remains the same, let us suppose the value of the flag determines the condition we need to check for comparing the current element. So, if the flag is 0 (or false) the current element should be smaller than the next and if the flag is 1 ( or true ) then the current element should be greater than the next. If not, swap the values of nodes.

Python3




# Python program for the above approach
# Node class
class Node:
   
    # Constructor to initialize the 
    # node object
    def __init__(self, data):
        self.data = data
        self.next = None
head = None
  
# Point Linked List
def printLL():
    t = head
    while (t != None):
        print(t.data, end = " ->")
        t = t.next
    print()
  
# Swap both nodes
def swap(a,b):
    if(a == None or 
       b == None):
        return
    temp = a.data
    a.data = b.data
    b.data = temp
  
# Rearrange the linked list
# in zig zag way
def zigZag(node, flag):
    if(node == None or 
       node.next == None):
        return node
    if (flag == 0):
        if (node.data > 
            node.next.data):
            swap(node, node.next)
        return zigZag(node.next, 1)
      
    else:
        if (node.data < 
            node.next.data):
            swap(node, node.next)
        return zigZag(node.next, 0)
  
# Driver Code
head =  Node(11)
head.next =  Node(15)
head.next.next =  Node(20)
head.next.next.next =  Node(5)
head.next.next.next.next =  Node(10)
printLL();
  
# 0 means the current element
# should be smaller than the next    
flag = 0
zigZag(head, flag)
print("LL in zig zag fashion : ")
printLL()
  
# This code is contributed by avanitrachhadiya2155


Output:

11 ->15 ->20 ->5 ->10 ->
LL in zig zag fashion : 
11 ->20 ->5 ->15 ->10 ->

Complexity Analysis: 

  • Time Complexity: O(n). 
    Traversal of the list is done only once, and it has ‘n’ elements.
  • Auxiliary Space: O(n). 
    O(n) extra space  dure to recursive stack.

Please refer complete article on Rearrange a Linked List in Zig-Zag fashion for more details!



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads