Sie sind auf Seite 1von 3

/*Solution 2):

Arjun Sharma
11135210
*/
class Element{
private int value;
private Element below = null;
public Element(int value){
this.value = value;
}
public int getValue(){ return this.value; }
public Element getBelow(){ return this.below; }
public void setBelow(Element e){
this.below = e;
}
public String toString(){
return this.value+"";
}
}
A particular type of element is a MinElement which extends the normal Element in
order to hold also a reference to the last MinElement:
1
2
3
4
5
6
7
8
9
10
class MinElement extends Element{
private MinElement lastMin;
public MinElement(int value, MinElement lastMin){
super(value);
this.lastMin = lastMin;
}
public MinElement getLastMin(){ return this.lastMin; }
}
Finally, the StackMin class which keeps the top Element and the current MinEleme
nt and implements the three functions: push, pop and min:
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
public class StackMin {
private Element top;
private MinElement currentMin;
public void push(Element item){
// Empty Stack = item is the new minimum
if(this.currentMin == null){
this.currentMin = new MinElement(item.getValue(), null);
this.top = this.currentMin;
return;
}
// Found a new minimum
if(currentMin.getValue() > item.getValue()){
MinElement newMin = new MinElement(item.getValue(), this.currentMin)
;
newMin.setBelow(this.top);
this.currentMin = newMin;
this.top = this.currentMin;
return;
}
// Normal push case
item.setBelow(this.top);
this.top = item;

}
public Element pop(){
// Empty Stack
if(this.currentMin == null){
return null;
}
Element ret = this.top;
// Current minimum on the top
if(this.top == this.currentMin){
this.currentMin = this.currentMin.getLastMin();
this.top = this.top.getBelow();
return ret;
}
// Normal pop case
this.top = ret.getBelow();
return ret;
}
public Element min(){
return currentMin;
}

Das könnte Ihnen auch gefallen