Professional Documents
Culture Documents
isEmpty
pop
push
…
Page 1 of 20
/*
* File: Stack.java
*/
Page 2 of 20
Concrete Implementation of the Stack ADT
(Version 2.0)
Page 4 of 20
elements[4]
elements[1]
elements[0]
count
2 3 6
6
3
2
Page 5 of 20
*
public void push(int element)
{
if (count == elements.length) {
int tmp[] = new int[elements.length+5];
System.arraycopy(elements, 0, tmp, 0, elements.length);
elements = tmp;
};
elements[count++]=element;
}
Page 6 of 20
Note:
z if (count == elements.length) {
int tmp[] = new int[elements.length+5];
System.arraycopy(elements,0,tmp,0,elements.length);
elements = tmp;
};
2 3 6 4 9
2 3 6 4 9
7 9
4
6 5
3
Page 7 of 20 2
The method System.arraycopy copies an array from the
specified source array, beginning at the specified position,
to the specified position of the destination array.
Page 8 of 20
The method System.arraycopy copies an array from the
specified source array, beginning at the specified position,
to the specified position of the destination array.
Page 9 of 20
The method System.arraycopy copies an array from the
specified source array, beginning at the specified position,
to the specified position of the destination array.
Page 10 of 20
Note:
z if (count == elements.length) {
int tmp[] = new int[elements.length+5];
System.arraycopy(elements,0,tmp,0,elements.length);
elements = tmp;
};
2 3 6
2 3 6 4 9
7 9
4
6 5
3
Page 11 of 20 2
Note:
z elements[count++]=element;
2 3 6 4 9 7
7 9
4
5 6
6
3
2
Page 12 of 20
public int pop()
{
return elements[--count]);
}
4
4
6
3
2
2 3 6 4 …
4 3
Page 13 of 20
public int stackDepth()
{
return count;
}
Page 14 of 20
Concrete Implementation of the Stack ADT
(Version 2.1)
One problem with version 2.0 is that the size of the stack
never reduces. This is not very efficient in terms of
memory usage.
Page 15 of 20
/* Version 2.1 */
Page 16 of 20
Note:
Page 17 of 20 6 5
/* Version 2.2 */
Page 18 of 20
/* Hey Exception */
public HeyException() {
super("Hey! Exception!");
}
Page 19 of 20
Using ADT’s in a Program
Page 20 of 20