Friday, October 25, 2013

STACK USING LINKED LIST.

/*

TOPIC: STACK USING LINKED LIST.
DATE:16/8/2012

*/
import java.io.*;
class Node
{
Object element;
Node next;

Node()
{
this(null,null);
}
Node(Object e,Node n)
{
element=e;
next=n;
System.out.println("A node is created");
}
Object getElement()
{
return element;
}
Node getNext()
{
return next;
}
void setElement(Object newEl)
{
element=newEl;
}
void setNext(Node newNext)
{
next=newNext;
}
}
class STACK
{
Node top;
int size;
STACK()
{
top=null;
size=0;
}
public int size()
{
return size;
}
void display() throws Exception
{
Node u=top;
if(isEmpty())
throw new Exception("cannot display as Stack is empty");
else
{
for(int i=0;u!=null;i++)
{
System.out.println(u.getElement());
u=u.next;
}
}
}
public boolean isEmpty()
{
if(top==null)
return true;
else return false;
}

void push(Object elem)
{
Node v=new Node();
v.setElement(elem);
v.setNext(top);
top=v;
size++;
}
public Object pop() throws Exception
{
if(isEmpty())
throw new Exception ("Stack is empty");
Object temp=top.getElement();
top=top.getNext();
size--;
return temp;
}

void destroy()
{
top=null;
System.gc();
}
}
class Demo
{
public static void main(String arg[])throws Exception
{
STACK s=new STACK();
int ch;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
one:for(int i=1;i>0;i++)
{
System.out.println();
System.out.println("1.push");

System.out.println("2.pop");
System.out.println("3.display");
System.out.println("4.Check empty");
System.out.println("5.Destroy");
System.out.println("6.exit");

ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("enter object");
Object o=br.readLine();
s.push(o);
break;
case 2:
System.out.println(s.pop()+"   was removed");
break;
case 3:
s.display();
break;
case 4:
System.out.println("STACK ISEMPTY: "+s.isEmpty());
break;
case 5:
s.destroy();
s=null;
System.gc();
break;
case 6:
System.out.println("thank you-coded by TG");
break one;
}
}
}
}
/*
OUTPUT:

1.push
2.pop
3.display
4.Check empty
5.Destroy
6.exit
1
enter object
t92
A node is created

1.push
2.pop
3.display
4.Check empty
5.Destroy
6.exit
1
enter object
fr.Agnels
A node is created

1.push
2.pop
3.display
4.Check empty
5.Destroy
6.exit
1
enter object
dj sanghvi
A node is created

1.push
2.pop
3.display
4.Check empty
5.Destroy
6.exit
1
enter object
atharva
A node is created

1.push
2.pop
3.display
4.Check empty
5.Destroy
6.exit
3
atharva
dj sanghvi
fr.Agnels
t92

1.push
2.pop
3.display
4.Check empty
5.Destroy
6.exit
4
STACK ISEMPTY: false

1.push
2.pop
3.display
4.Check empty
5.Destroy
6.exit
2
atharva   was removed

1.push
2.pop
3.display
4.Check empty
5.Destroy
6.exit
5

1.push
2.pop
3.display
4.Check empty
5.Destroy
6.exit
6
thank you-coded by TG
*/

No comments:

Post a Comment