Here I am creating 3 files 1. StackADT.java 2. SLStack.java 3. SLStack_Test.java
// Save the following StackADT inter face code with the above mentioned name
public interface StackADT
{
public int size();
public boolean isEmpty();
public Object top();
public void push(Object element);
public Object pop();
}
// 2. SLStack.java
import java.util.*;
class Node
{
public Object element;
public Node next;
public Node()
{
this(null,null);
}
public Node(Object element, Node next)
{
this.element=element;
this.next=next;
}
public Object getElement()
{
return element;
}
public Node getNode()
{
return next;
}
public void seElement(Object obj)
{
this.element=obj;
}
public void setNode(Node node)
{
this.next=node;
}
}
public class SLStack implements StackADT
{
private Node top;
private int size;
public boolean isEmpty()
{
return (size==0);
}
public void makeEmpty()
{
top=null;
size=0;
}
public Object pop()
{
if (top==null)
{
return null;
}
Object val=top.getElement();
top=top.getNode();
size--;
return val;
}
public void push(Object obj)
{
Node v=new Node(obj,top);
size++;
top=v;
}
public int size()
{
return size;
}
public Object top()
{
Node temp=top;
if(!isEmpty())
try
{
return temp.getElement();
}
catch (Exception e)
{
return e.getMessage();
}
else
return null;
//return null;
}
public void display()
{
Node current=top;
while (current!=null)
{
System.out.println(current.getElement());
current=current.next;
}
}
public void exit()
{
System.exit(0);
}
};
// 3. SLStack_Test.java
import java.util.*;
public class SLStack_Test
{
public static void main(String[] args)
{
int choice,el;
Scanner sc=new Scanner(System.in);
SLStack SLS=new SLStack();
//size=sc.nextInt();
while (true)
{
System.out.println("Please enter you choice\n");
System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
System.out.println(" 5 to display \n 6 to exit");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.print("Please enter Enter your element --> ");
el=sc.nextInt();
SLS.push(el);
System.out.println();
break;
case 2:
System.out.println(SLS.isEmpty());
break;
case 3:
if(!SLS.isEmpty())
{
System.out.println("top element is ");
System.out.println(SLS.top());
}
else
System.out.println("\nArray stack is empty\n");
break;
case 4:
System.out.println("\nPoped element is ");
System.out.print(SLS.pop());
System.out.println();
break;
case 5:
SLS.display();
break;
case 6:
SLS.exit();
default:
System.out.println("Please choose correct choice");
}
}
}
}
No comments:
Post a Comment