Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- typedef struct {
- int size;
- int capacity;
- int *stack;
- } node;
- /*
- * initNode(target):
- * Initialize a node with a dynamic stack that can handle two entries.
- * We pass in a reference to a node (Not a copy), so we can modify the
- * actual node.
- */
- void initNode(node *target) {
- target->size = 0;
- target->capacity = 2;
- /* Allocate memory for initial data. */
- target->stack = malloc(sizeof(int) * target->capacity);
- }
- /*
- * pushData(target, data):
- * Push data into the node. We first check if we need to allocate more
- * memory. Then we add the data.
- */
- void pushData(node *target, int data) {
- /* Reallocate memory if the stack is full. */
- if (target->size >= target->capacity) {
- target->capacity += 2;
- target->stack = realloc(target->stack, sizeof(int) * target->capacity);
- }
- /* Add data to stack. */
- target->stack[target->size] = data;
- /* Increment the size by one. */
- target->size++;
- }
- /*
- * getData(target, index):
- * Return data at index in our stack.
- */
- int getData(node *target, int index) {
- return (target->stack[index]);
- }
- /*
- * freeMemory(target):
- * Free our dynamically allocated memory so we don't have
- * any nasty memory leaks.
- */
- void freeMemory(node *target) {
- free (target->stack);
- }
- /*
- * main():
- * Main entry point of application.
- */
- int main(int argc, char *argv[]) {
- node dynamicStack;
- /* Initialize the stack. */
- initNode(&dynamicStack);
- /* Add some data to it. */
- pushData(&dynamicStack, 5);
- pushData(&dynamicStack, 93);
- pushData(&dynamicStack, 590);
- /* Get some data. */
- printf("Data at index 2: %d\n", getData(&dynamicStack, 2));
- printf("Data at index 0: %d\n", getData(&dynamicStack, 0));
- printf("Data at index 1: %d\n", getData(&dynamicStack, 1));
- freeMemory(&dynamicStack);
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement