{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

In this naive implementation it is not possible to

Info iconThis preview shows pages 10–11. Sign up to view the full content.

View Full Document Right Arrow Icon
In this naive implementation it is not possible to pop the stack in O (1) worst-case time. Indeed, if it so happens that the current minimum element is at the top of the stack and we pop it, then we need to update the theMin reference to point to the smallest element in the rest of the stack. This element could be anywhere so we need to traverse the whole stack to find it. This cannot be done in time O (1). ACTUAL SOLUTION: For the implementation we will use instead of the single reference theMin a data structure Aux containing several references to certain elements currently in S . Aux is another stack. NOT REQUIRED: Here is a picture of the contents of S and Aux after the sequence of operations push(3), push(4), push(2), push(5), push(1) assuming the stack was empty before this. | | | | | | | 4 | | | | 3 |<------|-* | | 3 |<------|-* | ----- ----- ----- ----- S Aux S Aux | | | | | 5 | | 2 |<--\ | | | 2 |<--\ | | | 4 | \--|-* | | 4 | \--|-* | | 3 |<------|-* | | 3 |<------|-* | ----- ----- ----- ----- S Aux S Aux | | | 1 |<--\ | 5 | \ | | | 2 |<--\ \-|-* | | 4 | \--|-* | | 3 |<------|-* | ----- ----- S Aux ACTUAL SOLUTION, CONTINUED: Now here is how we implement pop() : 10
Background image of page 10

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
(1) If the top of Aux points to the top of S then pop Aux . (2) Pop S . push(e) : (1) If e is bigger than the element in S to which the top of Aux points then push e onto S . (2) Otherwise ( e is smaller) push e onto S and push onto Aux a reference that points to the new top of S (containing e ). For findMin we return the element referred to by the top of Aux . 11
Background image of page 11
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}