Stack C and Data Structures Baojian Hua
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
Example: Stack of Char ‘a’‘a’ insert ‘b’‘b’ ‘a’‘a’ ‘b’‘b’ ‘a’‘a’ ‘c’‘c’ delete ‘b’‘b’ ‘a’‘a’
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
Implementation Using Extensible Array // in file “arrayStack.c” #include “arrayList.h” struct stackStruct { arrayList l; }; // Recall the “box” strategy: l stk
Operations: “ new ” stack newStack () { stack stk = (stack)malloc (sizeof (*stk)); stk->l = newArrayList (); return stk; } 0 n-1 array max tail l stk
Operations: “ size ” int size (stack stk) { return arrayListLength (stk->l); } 0 n-1 array max tail l stk
Operations: “ size ”, “ isEmpty ” int isEmpty (stack stk) { return arrayListIsEmpty (stk->l); } 0 n-1 array max tail l stk
Operations: “ push ” void push (stack stk, poly x) { arrayListInsertLast (stk->l, x); return; } 0 n-1 array max tail l stk
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
Implementation Using Linked List // in file “linkedStack.c” #include “linkedList.h” struct stackStruct { linkedList l; }; l stk
Operations: “ new ” stack newStack () { stack stk = (stack)malloc (sizeof (*stk)); stk->l = newLinkedList (); return stk; } l stk /\
Operations: “ size ” int size (stack stk) { return linkedListLength (stk->l); } l stk data next data next data next …
Operations: “ isEmpty ” int isEmpty (stack stk) { return linkedListIsEmpty (stk->l); } l stk data next data next data next …
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 …
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 …