Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stack C and Data Structures Baojian Hua

Similar presentations


Presentation on theme: "Stack C and Data Structures Baojian Hua"— Presentation transcript:

1 Stack C and Data Structures Baojian Hua bjhua@ustc.edu.cn

2 Linear List Recall that a linear list takes this form: The delete and insert operations may operate on an arbitrary element e_i If the delete and insert operations are restricted at (any) one end, we get a stack

3 Example: Stack of Char ‘a’‘a’ insert ‘b’‘b’ ‘a’‘a’ ‘b’‘b’ ‘a’‘a’ ‘c’‘c’ delete ‘b’‘b’ ‘a’‘a’

4 Abstract Data Types in C: Interface // in file “stack.h” #ifndef STACK_H #define STACK_H typedef struct stackStruct *stack; stack newStack (); int size (stack stk); int isEmpty (stack stk); void push (stack stk, poly x); poly pop (stack stk); poly getTop (stack stk); #endif

5 Implementation Using Extensible Array // in file “arrayStack.c” #include “arrayList.h” struct stackStruct { arrayList l; }; // Recall the “box” strategy: l stk

6 Operations: “ new ” stack newStack () { stack stk = (stack)malloc (sizeof (*stk)); stk->l = newArrayList (); return stk; } 0 n-1 array max tail l stk

7 Operations: “ size ” int size (stack stk) { return arrayListLength (stk->l); } 0 n-1 array max tail l stk

8 Operations: “ size ”, “ isEmpty ” int isEmpty (stack stk) { return arrayListIsEmpty (stk->l); } 0 n-1 array max tail l stk

9 Operations: “ push ” void push (stack stk, poly x) { arrayListInsertLast (stk->l, x); return; } 0 n-1 array max tail l stk

10 Operations: “ pop ” poly pop (stack stk) { if (arrayListIsEmpty (stk->l)) error (“empty stack”); return arrayListDeleteLast (stk->l); } 0 n-1 array max tail l stk

11 Implementation Using Linked List // in file “linkedStack.c” #include “linkedList.h” struct stackStruct { linkedList l; }; l stk

12 Operations: “ new ” stack newStack () { stack stk = (stack)malloc (sizeof (*stk)); stk->l = newLinkedList (); return stk; } l stk /\

13 Operations: “ size ” int size (stack stk) { return linkedListLength (stk->l); } l stk data next data next data next …

14 Operations: “ isEmpty ” int isEmpty (stack stk) { return linkedListIsEmpty (stk->l); } l stk data next data next data next …

15 Operations: “ push ” void push (stack stk, poly x) { // note the difference with extensible array linkedListInsertFirst (stk->l, x); return; } l stk data next data next data next …

16 Operations: “ pop ” poly pop (stack stk) { if (linkedListIsEmpty (stk->l)) error (“empty stack”); return linkedListDeleteFirst (stk->l); } l stk data next data next data next …


Download ppt "Stack C and Data Structures Baojian Hua"

Similar presentations


Ads by Google