Zig-Zag Linked List
rearrange Linked List such that converted list should be of the form a < b > c < d > e < f .
Idea is to traverse LL and check if it violates this rule then swap LL
Code:
public static void zigzag(Node head){
boolean flag=true;
while(head.next!=null)
{
if(flag)
{
if(head.data>head.next.data)
{int te=head.data;
head.data=head.next.data;
head.next.data=te;
}
}
else
{
if(head.data<head.next.data)
{int te=head.data;
head.data=head.next.data;
head.next.data=te;}
}
System.out.print(head.data+" ");
head=head.next;
flag=!flag;
}
System.out.println(head.data);
}
Idea is to traverse LL and check if it violates this rule then swap LL
Code:
public static void zigzag(Node head){
boolean flag=true;
while(head.next!=null)
{
if(flag)
{
if(head.data>head.next.data)
{int te=head.data;
head.data=head.next.data;
head.next.data=te;
}
}
else
{
if(head.data<head.next.data)
{int te=head.data;
head.data=head.next.data;
head.next.data=te;}
}
System.out.print(head.data+" ");
head=head.next;
flag=!flag;
}
System.out.println(head.data);
}
0 Comments:
Post a Comment