Given a Linked list, the task is to print a singly linked list in a spiral fashion, starting from the mid and rotating clockwise. If the linked list has even nodes, then you have to choose the left mid.
Naive Approach: There could be many approaches to solve this problem, one of the simplest approaches is here:
Storing the linked list data into ArrayList, and traversing the ArrayList by their indexes in spiral fashion.
Follow the given steps to solve the problem:
Create an ArrayList.
Traverse the linked list and insert the data in ArrayList.
Traverse it in a spiral fashion with two pointers, one from mid to left and the second from mid to end, one by one.
Following is the implementation of the above approach:
C++
#include<iostream>#include<vector>usingnamespacestd;classNode{public:intdata;Node*next;Node(intdata):data(data),next(nullptr){}};// Function to print the linked list in spiral ordervoidprintInSpiralForm(Node*head){vector<int>list;Node*t=head;// Traversing the linked list and adding data to the vectorwhile(t!=nullptr){list.push_back(t->data);t=t->next;}intn=list.size(),mid=(list.size()-1)/2;intleft=mid,right=mid+1;// Keep two pointers, one at mid, and the other at next to midwhile(left>=0||right<n){if(left>=0)cout<<list[left]<<" -> ";if(right<n)cout<<list[right]<<" -> ";left--;right++;}cout<<"X"<<endl;}// Driver codeintmain(){intarr[]={1,2,3,4,5,6};intn=sizeof(arr)/sizeof(arr[0]);Node*root=nullptr;// Create linked list from arrayfor(inti=0;i<n;i++){Node*temp=newNode(arr[i]);if(root==nullptr)root=temp;else{Node*ptr=root;while(ptr->next!=nullptr)ptr=ptr->next;ptr->next=temp;}}// Call the function to print in spiral formprintInSpiralForm(root);// Clean up memory (free nodes)while(root!=nullptr){Node*temp=root;root=root->next;deletetemp;}return0;}
Java
// Java code for the above approach:importjava.util.*;publicclassMain{staticclassNode{intdata;Nodenext;};// Function to print the linked list// in spiral orderpublicstaticvoidprintInSpiralForm(Nodehead){ArrayList<Integer>list=newArrayList<>();Nodet=head;// Traversing the linked list and adding// data to arraylistwhile(t!=null){list.add(t.data);t=t.next;}intn=list.size(),mid=(list.size()-1)/2;intleft=mid,right=mid+1;// Keep two pointers one at mid,// and 2nd at next to mid.while(left>=0||right<n){if(left>=0)System.out.print(list.get(left)+" -> ");if(right<n)System.out.print(list.get(right)+" -> ");left--;right++;}System.out.println("X");}// Driver codepublicstaticvoidmain(Stringargs[]){intarr[]={1,2,3,4,5,6};intn=arr.length;Noderoot=arrayToList(arr,n);printInSpiralForm(root);}// Driver code startsstaticNodeinsert(Noderoot,intitem){Nodetemp=newNode();Nodeptr;temp.data=item;temp.next=null;if(root==null)root=temp;else{ptr=root;while(ptr.next!=null)ptr=ptr.next;ptr.next=temp;}returnroot;}// Driver codestaticvoiddisplay(Noderoot){while(root!=null){System.out.print(root.data+" ");root=root.next;}}// Driver codestaticNodearrayToList(intarr[],intn){Noderoot=null;for(inti=0;i<n;i++)root=insert(root,arr[i]);returnroot;}}
Python3
classNode:def__init__(self,data):self.data=dataself.next=None# Function to print the linked list in spiral orderdefprint_in_spiral_form(head):lst=[]t=head# Traversing the linked list and adding data to a listwhilet:lst.append(t.data)t=t.nextn=len(lst)mid=(n-1)//2left=midright=mid+1# Keep two pointers, one at mid and the second at next to midwhileleft>=0orright<n:ifleft>=0:print(lst[left],'->',end=' ')ifright<n:print(lst[right],'->',end=' ')left-=1right+=1print("X")# Driver codeclassLinkedList:def__init__(self):self.head=Nonedefinsert(self,item):temp=Node(item)ifself.headisNone:self.head=tempelse:ptr=self.headwhileptr.next:ptr=ptr.nextptr.next=tempdefdisplay(self):root=self.headwhileroot:print(root.data,end=' ')root=root.nextdefarray_to_list(arr):ll=LinkedList()foriteminarr:ll.insert(item)returnll.headif__name__=="__main__":arr=[1,2,3,4,5,6]root=array_to_list(arr)print_in_spiral_form(root)#This code is Contributed by chinmaya121221
C#
// C# code for the above approach:usingSystem;usingSystem.Collections.Generic;classNode{publicintData;publicNodeNext;publicNode(intdata){Data=data;Next=null;}}classProgram{// Function to print the linked list in spiral orderstaticvoidPrintInSpiralForm(Nodehead){List<int>list=newList<int>();Nodet=head;// Traversing the linked list and adding data to the listwhile(t!=null){list.Add(t.Data);t=t.Next;}intn=list.Count;intmid=(list.Count-1)/2;intleft=mid;intright=mid+1;// Keep two pointers, one at mid, and the other at next to midwhile(left>=0||right<n){if(left>=0)Console.Write(list[left]+" -> ");if(right<n)Console.Write(list[right]+" -> ");left--;right++;}Console.WriteLine("X");}staticvoidMain(){int[]arr={1,2,3,4,5,6};intn=arr.Length;Noderoot=null;// Create linked list from arrayfor(inti=0;i<n;i++){NodenewNode=newNode(arr[i]);if(root==null){root=newNode;}else{Nodeptr=root;while(ptr.Next!=null){ptr=ptr.Next;}ptr.Next=newNode;}}// Call the function to print in spiral formPrintInSpiralForm(root);// Clean up memory (free nodes)while(root!=null){NodenextNode=root.Next;root.Next=null;// Release the noderoot=nextNode;}}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;}}// Function to print the linked list in spiral orderfunctionprintInSpiralForm(head){constlist=[];lett=head;// Traversing the linked list and adding data to the arraywhile(t!==null){list.push(t.data);t=t.next;}constn=list.length;constmid=Math.floor((list.length-1)/2);letleft=mid;letright=mid+1;// Keep two pointers, one at mid, and the other at next to midwhile(left>=0||right<n){if(left>=0){console.log(list[left]+' -> ');}if(right<n){console.log(list[right]+' -> ');}left--;right++;}console.log('X');}// Driver codefunctionmain(){constarr=[1,2,3,4,5,6];constn=arr.length;letroot=null;// Create linked list from arrayfor(leti=0;i<n;i++){consttemp=newNode(arr[i]);if(root===null){root=temp;}else{letptr=root;while(ptr.next!==null){ptr=ptr.next;}ptr.next=temp;}}// Call the function to print in spiral formprintInSpiralForm(root);// Clean up memory (free nodes)while(root!==null){consttemp=root;root=root.next;// Delete temp; (Garbage collection will handle this in JavaScript)}}main();
Output
3 -> 4 -> 2 -> 5 -> 1 -> 6 -> X
Time Complexity: O(N) Auxiliary Space: O(N)
Efficient Approach: To solve the problem follow the below idea:
Find mid. Reverse the linked list from start to mid. So that we can traverse it backwards also from mid to start, and traversing forwards from mid to end.
Follow the steps to solve the problem:
Find the mid of the list from where the spiral would start.
Reverse the list from the start to mid, so that we can traverse backwards from mid to left.
Lastly, traverse the list with two pointers from (mid to left) along with (mid+1 to right) one by one.
Following is the implementation of the above approach:
// Java code for the above approach:importjava.util.*;classNode{intdata;Nodenext=null;Node(intdata){this.data=data;}}publicclassSolution{staticNodehead=null,tail=null;publicstaticvoidmain(String[]args){int[]data=newint[]{1,2,3,4,5,6};createList(data);printInSpiralForm();head=null;tail=null;}staticvoidprintInSpiralForm(){// Function to print the list// in spiral formNodemid=getMiddleOfList(head);// Reversing the list from start to mid,// and storing the other half list// reference in nextToMid.NodenextToMid=reverseListTillMid(mid);print(head,nextToMid);}privatestaticNodegetMiddleOfList(Nodehead){// Finding mid with slow and fast pointerNodeslow=head,fast=head;// But we need the left middle in case// of order, so little modification// in the while conditionwhile(fast.next!=null&&fast.next.next!=null){slow=slow.next;fast=fast.next.next;}returnslow;}staticNodereverseListTillMid(Nodemid){Nodeprev=null,current=head,next=null;NodenextToMid=mid.next;// Need to reverse the list// till we encounter midwhile(current!=nextToMid){next=current.next;current.next=prev;prev=current;current=next;}head=prev;returnnext;}staticvoidprint(Nodehead,Nodesecondhead){// Printing list with// two pointers one by oneNodeitr1=head,itr2=secondhead;while(itr1!=null&&itr2!=null){System.out.print(itr1.data+" -> ");System.out.print(itr2.data+" -> ");itr1=itr1.next;itr2=itr2.next;}for(;itr1!=null;itr1=itr1.next)System.out.print(itr1.data+" -> ");System.out.print("X\n");}// Driver codestaticvoidcreateList(int[]data){for(vari:data){if(head==null){head=newNode(i);tail=head;}else{tail.next=newNode(i);tail=tail.next;}}}}
Python
from__future__importprint_function# For compatibility with Python 2.xclassNode:def__init__(self,data):self.data=dataself.next=Nonedefget_middle_of_list(head):slow=headfast=headwhilefast.nextisnotNoneandfast.next.nextisnotNone:slow=slow.nextfast=fast.next.nextreturnslowdefreverse_list_till_mid(mid):globalhead# Declare head as a global variableprev=Nonecurrent=headnext_node=Nonenext_to_mid=mid.nextwhilecurrent!=next_to_mid:next_node=current.nextcurrent.next=prevprev=currentcurrent=next_nodehead=prevreturnnext_to_middefprint_linked_lists(head,second_head):itr1=headitr2=second_headwhileitr1isnotNoneanditr2isnotNone:print(itr1.data," -> ",end="")print(itr2.data," -> ",end="")itr1=itr1.nextitr2=itr2.nextforitrin[itr1,itr2]:whileitrisnotNone:print(itr.data," -> ",end="")itr=itr.nextprint("X")defcreate_list(data):globalhead,tailforiinrange(len(data)):ifheadisNone:head=Node(data[i])tail=headelse:tail.next=Node(data[i])tail=tail.nextdefprint_in_spiral_form():mid=get_middle_of_list(head)next_to_mid=reverse_list_till_mid(mid)print_linked_lists(head,next_to_mid)if__name__=="__main__":head=Nonetail=Nonedata=[1,2,3,4,5,6]create_list(data)print_in_spiral_form()current=headwhilecurrentisnotNone:temp=currentcurrent=current.nextdeltemp
C#
usingSystem;classNode{publicintData{get;set;}publicNodeNext{get;set;}publicNode(intdata){Data=data;Next=null;}}classLinkedList{privateNodeHead{get;set;}// Points to the start of the linked listprivateNodeTail{get;set;}// Points to the end of the linked list// Get the head of the linked listpublicNodeGetHead(){returnHead;}// Find the middle node of the linked list using slow and fast pointerspublicNodeGetMiddleOfList(Nodehead){Nodeslow=head;Nodefast=head;while(fast?.Next!=null&&fast.Next.Next!=null){slow=slow.Next;fast=fast.Next.Next;}returnslow;}// Reverse the linked list from the head to the middle nodepublicNodeReverseListTillMid(Nodemid){Nodeprev=null;Nodecurrent=Head;Nodenext=null;NodenextToMid=mid.Next;while(current!=nextToMid){next=current.Next;current.Next=prev;prev=current;current=next;}Head=prev;returnnextToMid;}// Print two linked lists in a spiral formpublicvoidPrint(Nodehead,NodesecondHead){Nodeitr1=head;Nodeitr2=secondHead;while(itr1!=null&&itr2!=null){Console.Write(itr1.Data+" -> ");Console.Write(itr2.Data+" -> ");itr1=itr1.Next;itr2=itr2.Next;}for(;itr1!=null;itr1=itr1.Next){Console.Write(itr1.Data+" -> ");}Console.WriteLine("X");}// Create a linked list from an array of integerspublicvoidCreateList(int[]data){for(inti=0;i<data.Length;i++){if(Head==null){Head=newNode(data[i]);Tail=Head;}else{Tail.Next=newNode(data[i]);Tail=Tail.Next;}}}// Print the linked list in a spiral formpublicvoidPrintInSpiralForm(){Nodemid=GetMiddleOfList(Head);// Find the middle of the listNodenextToMid=ReverseListTillMid(mid);// Reverse the list till the middlePrint(Head,nextToMid);// Print in a spiral form}}classProgram{staticvoidMain(){int[]data={1,2,3,4,5,6};LinkedListlist=newLinkedList();list.CreateList(data);// Create a linked list from the arrayNodehead=list.GetHead();// Get the head nodelist.PrintInSpiralForm();// Print the linked list in spiral form// Clean up memory (free nodes)Nodecurrent=head;while(current!=null){current=current.Next;// No need for a temporary variable}}}
JavaScript
classNode{constructor(data){this.data=data;// Node's datathis.next=null;// Pointer to the next node}}classLinkedList{constructor(){this.head=null;// Points to the start of the linked listthis.tail=null;// Points to the end of the linked list}// Create a linked list from an array of data elementscreateList(data){for(leti=0;i<data.length;i++){if(!this.head){this.head=newNode(data[i]);// Create the first node if head is nullthis.tail=this.head;// Set the tail as the head initially}else{this.tail.next=newNode(data[i]);// Add a new node to the end of the listthis.tail=this.tail.next;// Update the tail to the new node}}}// Find the middle node of the linked list using slow and fast pointersgetMiddleOfList(head){letslow=head;// Slow pointer starts at the headletfast=head;// Fast pointer starts at the headwhile(fast?.next&&fast.next.next){slow=slow.next;// Move slow pointer by one nodefast=fast.next.next;// Move fast pointer by two nodes}returnslow;// Return the middle node using the slow pointer}// Reverse the linked list from the head to the middle nodereverseListTillMid(mid){letprev=null;letcurrent=this.head;letnext=null;letnextToMid=mid.next;// Next to the middle nodewhile(current!==nextToMid){next=current.next;// Store the next nodecurrent.next=prev;// Reverse the pointerprev=current;// Move to the next nodecurrent=next;// Move to the next node}this.head=prev;// Update the head of the listreturnnextToMid;// Return the node next to the middle}// Print nodes of two linked lists in a spiral formprint(head,secondHead){letitr1=head;letitr2=secondHead;while(itr1&&itr2){console.log(itr1.data+" -> "+itr2.data+" -> ");// Print elements from both listsitr1=itr1.next;// Move to the next node in the first listitr2=itr2.next;// Move to the next node in the second list}for(;itr1;itr1=itr1.next){console.log(itr1.data+" -> ");// Print remaining nodes of the first list}console.log("X");// End of the list}// Print the linked list in a spiral formprintInSpiralForm(){constmid=this.getMiddleOfList(this.head);// Find the middle of the listconstnextToMid=this.reverseListTillMid(mid);// Reverse the list till the middlethis.print(this.head,nextToMid);// Print in a spiral form}}constdata=[1,2,3,4,5,6];constlist=newLinkedList();list.createList(data);// Create a linked list from the arraylist.printInSpiralForm();// Print the linked list in spiral form
Output
3 -> 4 -> 2 -> 5 -> 1 -> 6 -> X
Time complexity: O(N) Auxiliary Space: O(1), since no extra space is used.