exercise 6 : stack 1.stack is a data structure that supports lifo (last in first out) operations. -...
TRANSCRIPT
Exercise 6 : Stack1. 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
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);
Stack_main.c
#include <stdio.h>
#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;
}
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 ofdata push() and pop() whilePreserving memory efficiency
Implement Stack.c#include "stack.h"
#include <stdlib.h>
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
}
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.