Download presentation
Presentation is loading. Please wait.
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 Stack_t *Stack_t; Stack_t Stack_new (); int Stack_size (Stack_t stk); int Stack_isEmpty (Stack_t stk); void Stack_push (Stack_t stk, poly x); poly Stack_pop (Stack_t stk); poly Stack_getTop (Stack_t stk); #endif
5
Implementation Using Extensible Array // in file “arrayStack.c” #include “array.h” struct Stack_t { Array_t l; }; // Recall the “box” strategy: l stk
6
Operations: “ new ” Stack_t Stack_new () { Stack_t stk = malloc (sizeof (*stk)); stk->l = ArrayList_new (); return stk; } 0 n-1 array max tail l stk
7
Operations: “ size ” int Stack_size (Stack_t stk) { return Array_length (stk->l); } 0 n-1 array max tail l stk
8
Operations: “ size ”, “ isEmpty ” int Stack_isEmpty (Stack_t stk) { return Array_isEmpty (stk->l); } 0 n-1 array max tail l stk
9
Operations: “ push ” void Stack_push (Stack_t stk, poly x) { Array_insertLast (stk->l, x); return; } 0 n-1 array max tail l stk
10
Operations: “ pop ” poly Stack_pop (Stack_t stk) { if (Array_isEmpty (stk->l)) error (“empty stack”); return Array_deleteLast (stk->l); } 0 n-1 array max tail l stk
11
Implementation Using Linked List // in file “linkedStack.c” #include “linkedList.h” struct Stack_t { List_t l; }; l stk
12
Operations: “ new ” Stack_t Stack_new () { Stack_t stk = malloc (sizeof (*stk)); stk->l = LinkedList_new (); return stk; } l stk /\
13
Operations: “ size ” int Stack_size (Stack_t stk) { return LinkedList_length (stk->l); } l stk data next data next data next …
14
Operations: “ isEmpty ” int Stack_isEmpty (Stack_t stk) { return LinkedList_isEmpty (stk->l); } l stk data next data next data next …
15
Operations: “ push ” void Stack_push (Stack_t stk, poly x) { // note the difference with extensible array LinkedList_insertFirst (stk->l, x); return; } l stk data next data next data next …
16
Operations: “ pop ” poly Stack_pop (Stack_t stk) { if (LinkedList_isEmpty (stk->l)) error (“empty stack”); return LinkedList_deleteFirst (stk->l); } l stk data next data next data next …
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.