06Stacks - CS 240 Chapter 6 - Stacks CS 240 Chapter 6 -...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CS 240 Chapter 6 - Stacks CS 240 Chapter 6 - Stacks 1Page 1 Chapter 6 Stacks The stack abstract data type is essentially a list using the LIFO (last-in- first-out) policy for adding and removing elements. The principal stack operations: Create an empty stack. Copy an existing stack. Destroy a stack. Determine whether a stack is empty. Add a new element to a stack. Remove the most recently added element from a stack. Retrieve the most recently added element from a stack. CS 240 Chapter 6 - Stacks CS 240 Chapter 6 - Stacks 2Page 2 When running a program that uses functions, a stack is used to keep track of the function calls, including the status of the variables in each function. Example Stack Application #1: The Run-Time Stack void main() { int x = 20; int y = 30; int z = 10; if ((x > y) || (y > z)) reorder(x,y,z); cout << x << y << z; } x: ? y: ? z: ? x: 20 y: 30 z: 10 void reorder(int &a, int &b, int &c) { if ((b <= a) && (b <= c)) swap(a,b); else if ((c <= a) && (c <= b)) swap(a,c); if (b <= c) swap(b,c); } a: 20 b: 30 c: 10 void main() { int x = 20; int y = 30; int z = 10; if ((x > y) || (y > z)) reorder(x,y,z); cout << x << y << z; } x: 20 y: 30 z: 10 void swap(int &u, int &v) { int temp = u; u = v; v = temp; } u: 20 v: 10 temp: ? void reorder(int &a, int &b, int &c) { if ((b <= a) && (b <= c)) swap(a,b); else if ((c <= a) && (c <= b)) swap(a,c); if (b <= c) swap(b,c); } a: 20 b: 30 c: 10 void main() { int x = 20; int y = 30; int z = 10; if ((x > y) || (y > z)) reorder(x,y,z); cout << x << y << z; } x: 20 y: 30 z: 10 x: 10 z: 20 u: 10 v: 20 temp: 20 a: 10 c: 20 void reorder(int &a, int &b, int &c) { if ((b <= a) && (b <= c)) swap(a,b); else if ((c <= a) && (c <= b)) swap(a,c); if (b <= c) swap(b,c); } a: 10 b: 30 c: 20 void main() { int x = 20; int y = 30; int z = 10; if ((x > y) || (y > z)) reorder(x,y,z); cout << x << y << z; } x: 10 y: 30 z: 20 void swap(int &u, int &v) { int temp = u; u = v; v = temp; } u: 30 v: 20 temp: ?...
View Full Document

Page1 / 8

06Stacks - CS 240 Chapter 6 - Stacks CS 240 Chapter 6 -...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online