Download presentation
Presentation is loading. Please wait.
Published byEleanore Lawson Modified over 9 years ago
1
Exercise 6 : Stack 1.Stack is a data structure that supports LIFO (Last In First Out) operations. - In this exercise, you implement Stack data structures (1) using array (fixed size) (2) using dynamically growing memory management -Through the implementation and execution of the codes, try to understand (i)how to implement a stack (ii)how to apply “struct” to stack implementation (iii)how to do dynamically growing memory (iv)benefits of using dynamic allocation for stack
2
Implementation of Stack Interface design Stack *mkStack(); void push(Stack *s, int item); int pop(Stack *s); int isEmpty(const Stack *s); int isFull(const Stack *s);
3
Stack_main.c #include #include "stack.h" int main() { int data; int n, i; Stack *s; printf("Get # of input : "); scanf("%d", &n); s = mkStack(); printf("%d integer input : ", n); for (i = 0; i < n; ++i) { scanf("%d", &data); push(s, data); } printf("printed in reverse order: "); while (! isEmpty(s)) { data = pop(s); printf("%d ", data); } printf("\n"); return 0; }
4
Stack.h #define MAX_SIZE 10 struct _stack { int data[MAX_SIZE]; int top; }; typedef struct _stack Stack; Stack *mkStack(); void push(Stack *s, int item); int pop(Stack *s); int isEmpty(const Stack *s); int isFull(const Stack *s); void error(const char *msg); Using Array (fixed size) #define MAX_SIZE 10 struct _stack { int *data; int top; int size; }; typedef struct _stack Stack; Stack *mkStack(); void push(Stack *s, int item); int pop(Stack *s); int isEmpty(const Stack *s); int isFull(const Stack *s); void error(const char *msg); Dynamically growing memory Allows arbitrary number of data push() and pop() while Preserving memory efficiency
5
Implement Stack.c #include "stack.h" #include void error(const char *msg) { printf("error : %s ",msg); printf(“Program Finished.\n"); exit(-1); } Stack * mkStack() { // insert your code } void push(Stack *s, int item) { // insert your code } int pop(Stack *s) { // insert your code } int isEmpty(const Stack *s) { // insert your code } int isFull(const Stack *s) { // insert your code }
6
Related C functions void* malloc ( size_t size ); Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. void* realloc ( void * ptr, size_t size ); The size of the memory block pointed to by the ptr parameter is changed to the size bytes, expanding or reducing the amount of memory available in the block. Returns a pointer to the expanded or reduced memory area void* memcpy(void *d, const void * s, size_t num); Copies num bytes from the location pointed by source s directly to the memory block pointed by destination d. void* memset(void * ptr, int value, size_t num); Sets the first num bytes of the block of memory pointed by ptr to the specified value.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.