Stack C and Data Structures Baojian Hua bjhuaustc
Stack C and Data Structures Baojian Hua bjhua@ustc. edu. cn
Linear List n Recall that a linear list takes this form: n n 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 insert delete ‘c’ ‘a’ ‘b’ ‘b’ ‘a’ ‘a’
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_is. Empty (Stack_t stk); void Stack_push (Stack_t stk, poly x); poly Stack_pop (Stack_t stk); poly Stack_get. Top (Stack_t stk); #endif
Implementation Using Extensible Array // in file “array. Stack. c” #include “array. h” struct Stack_t { Array_t l; }; // Recall the “box” strategy: stk l
Operations: “new” Stack_t Stack_new () { Stack_t stk = malloc (sizeof (*stk)); stk->l = Array. List_new (); stk return stk; } l array max tail 0 n-1
Operations: “size” int Stack_size (Stack_t stk) { return Array_length (stk->l); } stk l array max tail 0 n-1
Operations: “size”, “is. Empty” int Stack_is. Empty (Stack_t stk) { return Array_is. Empty (stk->l); } stk l array max tail 0 n-1
Operations: “push” void Stack_push (Stack_t stk, poly x) { Array_insert. Last (stk->l, x); return; } stk array l max tail 0 n-1
Operations: “pop” poly Stack_pop (Stack_t stk) { if (Array_is. Empty (stk->l)) error (“empty stack”); return Array_delete. Last (stk->l); stk } array l max tail 0 n-1
Implementation Using Linked List // in file “linked. Stack. c” #include “linked. List. h” struct Stack_t { List_t l; }; stk l
Operations: “new” Stack_t Stack_new () { Stack_t stk = malloc (sizeof (*stk)); stk->l = Linked. List_new (); return stk; } stk l / /
Operations: “size” int Stack_size (Stack_t stk) { return Linked. List_length (stk->l); } stk l data next …
Operations: “is. Empty” int Stack_is. Empty (Stack_t stk) { return Linked. List_is. Empty (stk->l); } stk l data next …
Operations: “push” void Stack_push (Stack_t stk, poly x) { // note the difference with extensible array Linked. List_insert. First (stk->l, x); return; } stk l data next …
Operations: “pop” poly Stack_pop (Stack_t stk) { if (Linked. List_is. Empty (stk->l)) error (“empty stack”); return Linked. List_delete. First (stk->l); } stk l data next …
- Slides: 16