18.10.2014 Views

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

218 Polymorphism<br />

procedure Push( The:<strong>in</strong> out Stack; Item:<strong>in</strong> Stack_Element ) is<br />

Tmp : P_Node;<br />

--Allocated node<br />

beg<strong>in</strong><br />

Tmp := new Node'(Item=>Item, P_Next=>The.P_Head);<br />

The.P_Head := Tmp;<br />

end Push;<br />

Pop extracts the top item from the stack, and then releases the storage for this element back to the system.<br />

The cha<strong>in</strong> of elements after add<strong>in</strong>g 3 and<br />

2 to an <strong>in</strong>stance of the Stack<br />

The cha<strong>in</strong> of elements after popp<strong>in</strong>g the<br />

top element<br />

P_Head<br />

P_Head<br />

Tmp<br />

2<br />

2<br />

3<br />

3<br />

procedure Pop( The:<strong>in</strong> out Stack; Item :out Stack_Element ) is<br />

Tmp : P_Node;<br />

--Free node<br />

beg<strong>in</strong><br />

if The.P_Head /= null then --if item then<br />

Tmp := The.P_Head; --isolate top node<br />

Item := The.P_Head.Item; --extract item stored<br />

The.P_Head := The.P_Head.P_Next; --Rel<strong>in</strong>k<br />

Dispose( Tmp );<br />

--return storage<br />

else<br />

raise Stack_Error; --Failure<br />

end if;<br />

end Pop;<br />

The procedure reset pops all exist<strong>in</strong>g elements from the stack. Remember the procedure pop releases the<br />

storage for the held item.<br />

procedure Reset( The:<strong>in</strong> out Stack ) is<br />

Tmp : Stack_Element;<br />

beg<strong>in</strong><br />

while The.P_Head /= null loop<br />

Pop( The, Tmp );<br />

end loop;<br />

end Reset;<br />

--Re-<strong>in</strong>itialize stack<br />

end Class_Stack;<br />

© M A Smith - May not be reproduced without permission

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!