mavadah 18.8
package stack_unit4;
import java.util.Scanner;
import unit4.collectionsLib.*;
public class mabada1 {
public static BinNode<Integer> ex1(BinNode<Integer>first,int num)//O(n)
{
BinNode<Integer>t = new BinNode(num);
if(first==null)
return t;
first.setLeft(t);
t.setRight(first);
return t;
}
public static BinNode<Integer> ex2(BinNode<Integer>first,int num)//O(n)
{
BinNode<Integer>t = new BinNode(num);
if(first==null)
return t;
BinNode<Integer>hold=first;
while(hold.getRight()!=null)
{
hold=hold.getRight();
}
hold.setRight(t);
t.setLeft(first);
return first;
}
public static BinNode<Integer> ex3(int num)//O(n)
{
BinNode<Integer> first=null, last=null, t;
for(int i =num;i>0;i--)
{
t = new BinNode<Integer>(i);
if(first==null)
first=last=t;
else
{
last.setRight(t);
t.setLeft(last);
last=t;
}
}
return first;
}
public static void ex4(BinNode<Integer>first)//O(n)
{
System.out.print("null<->");
while (first !=null)
{
System.out.print(first+"<->");
first = first.getRight();
}
System.out.println("null");
}
public static boolean ex5(BinNode<Integer> n) {//o(n)
BinNode<Integer> first=n,temp=n,last=temp;
//in case of single node
if(first.getRight()==null)return true;
//get last
while(temp!=null) {
last=temp;
temp=temp.getRight();
}
//compare From 2 ends until we reach the middle
do {
if(first.getValue()!=last.getValue())return
false;
first=first.getRight();
last=last.getLeft();
}
while(first.getRight()!=last.getLeft());
return true;
}
public static void main(String[] args)
{
BinNode<Integer> b =ex3(10);
BinNode<Integer> a =ex3(10);
ex4(b);
b=ex1(b,10);
ex4(b);
b=ex2(b,10);
ex4(b);
System.out.println(ex5(a));
}
}