-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack using LinkedList
More file actions
85 lines (82 loc) · 1.97 KB
/
Copy pathStack using LinkedList
File metadata and controls
85 lines (82 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.LinkedList;
import java.util.*;
class GenericStackLinked1<T>{
private LinkedList<T> stack;
public GenericStackLinked1(){
stack=new LinkedList<>();
}
public void push(T element){
stack.addFirst(element);
}
public T pop(){
if(stack.isEmpty()){
System.out.println("stack underflow");
return null;
}
return stack.removeFirst();
}
public T peek(){
if(stack.isEmpty()){
System.out.println("Stack is Empty");
return null;
}
return stack.getFirst();
}
public boolean isEmpty(){
return stack.isEmpty();
}
public void displayStack(){
if(stack.isEmpty()){
System.out.println("Stack is Empty");
}
else{
System.out.println("Stack Elements:"+stack);
//System.out.print("address"+System.identityHashCode(ele));
}
}
}
public class GenericStackLinked{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
GenericStackArray1<Integer> stringstack=new GenericStackArray1<>();
System.out.println("Dyanmically Generic stack using LinkedList");
while(true){
System.out.println("\n choose an operation\n");
System.out.println("1.push");
System.out.println("2.pop\n");
System.out.println("3.peek\n");
System.out.println("4.display");
System.out.println("5.Exit");
int ch=sc.nextInt();
sc.nextLine();
switch(ch){
case 1 :
System.out.print("Enter the element to push");
int ele=sc.nextInt();
stringstack.push(ele);
break;
case 2:
int poppedele=stringstack.pop();
if(poppedele!=-1){
System.out.println("Popped ele :"+poppedele);
}
break;
case 3:
Integer topele=stringstack.peek();
if(topele!=null){
System.out.println("Top elem:"+topele);
}
break;
case 4:
stringstack.displayStack();
break;
case 5:
System.out.println("Exiting...");
sc.close();
return;
default:
System.out.println("Invalid choice");
}
}
}
}