forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stackll.java
89 lines (88 loc) · 1.99 KB
/
Stackll.java
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
86
87
88
89
//Stack implemetation Its readme file in wiki
import java.util.*;
import java.lang.*;
class mystack<E>
{
static class Node<E> {
E data;
Node<E> next;
Node(E data) {
this.data = data;
next = null;
}
}
Node<E> head;
Node<E> top;
int c=0;
boolean isempty(){ return head==null;}
void push(E a){
Node<E> temp=new Node<E>(a);
Node<E> temp1=head;
if(isempty()){
head=temp;
top=head;
c++;
return;
}
else{
while(temp1.next!=null){
temp1=temp1.next;
}
temp1.next=temp;
c++;
top=temp;
}
}
E peek(){
if(isempty())
return null;
return top.data;
}
E pop() throws Exception{
if(isempty()){
throw new Exception("eeempty");
}
else if(head==top){
Node<E> temp1=head;
head=top=null;
return temp1.data;
}
else{
Node<E> temp1=head;
Node<E> temp;
while(temp1.next.next!=null){
temp1=temp1.next;
}
temp=temp1.next;
temp1.next=null;
top=temp1;
c--;
return temp.data;
}
}
}
public class Stackll {
public static void main(String[] args) throws Exception {
mystack<Integer> s = new mystack<Integer>();
s.push(1);
s.push(2);
s.push(3);
System.out.println(s.peek());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.peek());
System.out.println(s.pop());
}
}
/*
output:
3
3
2
1
null
Exception in thread "main" java.lang.Exception: eeempty
at mystack.pop(Stackll.java:43)
at Stackll.main(Stackll.java:76)
*/