Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Push and Pop Methods, Top Property

Program gif defines the Push and Pop methods and the Top property of the StackAsArray class. The first of these, Push, adds an element to the stack. It takes as its argument the object to be pushed onto the stack.

   program5382
Program: StackAsArray class Push and Pop Methods, Top property.

The Push method first checks to see if there is room left in the stack. If no room is left, it throws a ContainerFullException exception. Otherwise, it simply puts the object into the array, and then increases the count variable by one. In a correctly functioning program, stack overflow should not occur. If we assume that overflow does not occur, the running time of the Push method is clearly O(1).

The Pop method removes an item from the stack and returns that item. The Pop method first checks if the stack is empty. If the stack is empty, it throws a ContainerEmptyException exception. Otherwise, it simply decreases count by one and returns the item found at the top of the stack. In a correctly functioning program, stack underflow will not occur normally. The running time of the Pop method is O(1).

Finally, the Top property provides a get accessor that returns the top item in the stack. The get accessor does not modify the stack. In particular, it does not remove the top item from the stack. The Top method first checks if the stack is empty. If the stack is empty, it throws a ContainerEmptyException exception. Otherwise, it returns the top item, which is found at position tex2html_wrap_inline60457 in the array. Assuming stack underflow does not occur normally, the running time of the Top method is O(1).


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.