STACKS QUEUES Prof Michael Tsai 201236 4 function

  • Slides: 34
Download presentation
STACKS & QUEUES Prof. Michael Tsai 2012/3/6

STACKS & QUEUES Prof. Michael Tsai 2012/3/6

4 例子一: 系統堆疊 • 被程式拿來儲存呼叫function的相 關資訊 • 放什麼? 叫做activation record或 stack frame • return

4 例子一: 系統堆疊 • 被程式拿來儲存呼叫function的相 關資訊 • 放什麼? 叫做activation record或 stack frame • return address: 呼叫function的下一個 指令應該去的地方 • previous frame pointer: 指到前一個 stack frame在stack裡面的位置(底) • local variables Previous frame pointer Return address • 看一個例子. sp • 適不適用recursive call? • Stack overflow? fp Local variables Previous frame pointer Return address

6 Code struct Array. Stack { int top; int capacity; int *array; } struct

6 Code struct Array. Stack { int top; int capacity; int *array; } struct Array. Stack *Create. Stack() { struct Array. Stack *S = malloc(sizeof(struct Array. Stack)); if (!S) return NULL; S->capacity=4; S->top=-1; S->array=(int*)malloc(S->capacity*sizeof(int)) if (!S->array) return NULL; return S; }

7 Code void Push(struct Array. Stack*S, int data) { if (Is. Full. Stack(S)) printf(“Stack

7 Code void Push(struct Array. Stack*S, int data) { if (Is. Full. Stack(S)) printf(“Stack Over. Flow”); else S->array[++S->top]=data; } int Pop(struct Array. Stack*S) { if (Is. Empty. Stack(S)) { printf(“Stack is Empty”); return 0; } else return (S->array[S->top--]); }