Advertisement
Guest User

Untitled

a guest
Feb 9th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.83 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. typedef struct {
  4.     int     size;
  5.     int     capacity;
  6.     int     *stack;
  7. } node;
  8.  
  9. /*
  10.  * initNode(target):
  11.  *  Initialize a node with a dynamic stack that can handle two entries.
  12.  *  We pass in a reference to a node (Not a copy), so we can modify the
  13.  *  actual node.
  14.  */
  15. void initNode(node *target) {
  16.     target->size = 0;
  17.     target->capacity = 2;
  18.  
  19.     /* Allocate memory for initial data. */
  20.     target->stack = malloc(sizeof(int) * target->capacity);
  21. }
  22.  
  23. /*
  24.  * pushData(target, data):
  25.  *  Push data into the node. We first check if we need to allocate more
  26.  *  memory. Then we add the data.
  27.   */
  28. void pushData(node *target, int data) {
  29.     /* Reallocate memory if the stack is full. */
  30.     if (target->size >= target->capacity) {
  31.         target->capacity += 2;
  32.         target->stack = realloc(target->stack, sizeof(int) * target->capacity);
  33.     }
  34.  
  35.     /* Add data to stack. */
  36.     target->stack[target->size] = data;
  37.  
  38.     /* Increment the size by one. */
  39.     target->size++;
  40. }
  41.  
  42. /*
  43.  * getData(target, index):
  44.  *  Return data at index in our stack.
  45.  */
  46. int getData(node *target, int index) {
  47.     return (target->stack[index]);
  48. }
  49.  
  50. /*
  51.  * freeMemory(target):
  52.  *  Free our dynamically allocated memory so we don't have
  53.  *  any nasty memory leaks.
  54.  */
  55. void freeMemory(node *target) {
  56.     free (target->stack);
  57. }
  58.  
  59. /*
  60.  * main():
  61.  *  Main entry point of application.
  62.  */
  63. int main(int argc, char *argv[]) {
  64.     node dynamicStack;
  65.  
  66.     /* Initialize the stack. */
  67.     initNode(&dynamicStack);
  68.  
  69.     /* Add some data to it. */
  70.     pushData(&dynamicStack, 5);
  71.     pushData(&dynamicStack, 93);
  72.     pushData(&dynamicStack, 590);
  73.  
  74.     /* Get some data. */
  75.     printf("Data at index 2: %d\n", getData(&dynamicStack, 2));
  76.     printf("Data at index 0: %d\n", getData(&dynamicStack, 0));
  77.     printf("Data at index 1: %d\n", getData(&dynamicStack, 1));
  78.  
  79.     freeMemory(&dynamicStack);
  80.  
  81.     return (0);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement