-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackImplement.java
More file actions
117 lines (95 loc) · 2.13 KB
/
Copy pathstackImplement.java
File metadata and controls
117 lines (95 loc) · 2.13 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
public class stackImplement implements stackADT{
/**
* represent the default capacity of the array
*/
public final int DEFAULT_CAP = 7;
/**
* int representing number of elements and the next position in array
*/
private int top;
/**
* array of generic elements to represent the stack
*/
private double[] stack;
/**
* Create an empty stack using default
*/
public stackImplement(){
top = 0;
stack = new double[DEFAULT_CAP];
}
/**
* create an empty stack using the specified cap.
*/
public stackImplement(int number){
top = 0;
stack = new double[number];
}
/**
* return top as size of stack
*/
public int size(){
return top;
}
/**
* expand the capacity of the array
*/
public void expandCapacity(){
double[] larger = new double [stack.length * 2];
// set all elements to be now set in the new larger array
for (int i = 0; i < stack.length; i ++){
larger[i] = stack[i];
}
// set larger to become default
stack = larger;
}
/**
* adds the element to the top of the stack
*/
public void push(double mark){
if (size() == stack.length){
expandCapacity();
}
stack[top] = mark;
top++;
}
public void push(double mark, double weight){
double grade = mark * weight;
if (size() == stack.length){
expandCapacity();
}
stack[top] = grade;
top++;
}
/**
* return true if the stack is empty
*/
public boolean isEmpty(){
return (top == 0);
}
/**
* removes the element on the top of the stack and returning a reference
* throw an emptycollection exception if the stack is empty
*/
public double pop() throws EmptyCollectionException{
if (isEmpty()){
throw new EmptyCollectionException("Stack");
}
// decrement top
top--;
// store stack[top] element into result
double result = stack[top];
//set element to 0.0
stack[top] = 0.0;
return result;
}
/**
* returns a reference to the element at the top of the stack. Element is not removed from the stack
*/
public double peek(){
if (isEmpty()){
throw new EmptyCollectionException("Stack");
}
return stack[top-1];
}
}