File: Stack.java
------------------------------------------------------------------
package org.developersbrain.solutions;
class DataNode<T>{
T t;
DataNode<T> next;
DataNode(T t){
this.t=t;
}
}
public class Stack<T> {
DataNode<T> top;
Stack(){
top=null;
}
protected void push(T t){
DataNode<T> newN=new DataNode<T>(t);
if(top==null){
top=newN;
}else{
newN.next=top;
top=newN;
}
}
private DataNode<T> pop(){
if(top==null) return null;
DataNode<T> popNode=top;
top=top.next;
return popNode;
}
protected void popElement(){
DataNode<T> data=pop();
System.out.println(data.t);
}
protected void printStack(){
DataNode<T> printer=top;
while(printer!=null){
System.out.println(printer.t);
printer=printer.next;
}
}
}
File:MainClass.java
----------------------------------------------
package org.developersbrain.solutions;
public class MainClass {
public static void main(String[] args){
Stack<Integer> stckNumbers=new Stack<Integer>();
stckNumbers.push(10);
stckNumbers.push(20);
stckNumbers.push(30);
stckNumbers.push(40);
stckNumbers.push(50);
stckNumbers.push(60);
stckNumbers.push(70);
stckNumbers.push(80);
System.out.println("Stack Elements");
System.out.println("------------------------------------");
stckNumbers.printStack();
System.out.println();
System.out.println("Remove element from the Stack");
System.out.println("------------------------------------");
stckNumbers.popElement();
System.out.println();
System.out.println("Print the modified Stack");
System.out.println("------------------------------------");
stckNumbers.printStack();
}
}
Output:
----------------------
Stack Elements
------------------------------------
80
70
60
50
40
30
20
10
Remove element from the Stack
------------------------------------
80
Print the modified Stack
------------------------------------
70
60
50
40
30
20
10
Comments
Post a Comment