hozer

DDS - Stack (1-way linked list)

May 29th, 2014
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.95 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <conio.h>
  4.  
  5. typedef struct _node {
  6.     int data;
  7.     struct _node *next;
  8. } node;
  9.  
  10. node *Push(node *head, int data)
  11. {
  12.     node *nNode;
  13.     nNode = (node*) malloc(sizeof(node));
  14.     nNode->data = data;
  15.     nNode->next = NULL;
  16.     if (head)
  17.         nNode->next = head;
  18.     head = nNode;
  19.     return head;
  20. }
  21.  
  22. node *Pop(node *head)
  23. {
  24.     node *temp = head;
  25.     head = head->next;
  26.     free(temp);
  27.     return head;
  28. }
  29.  
  30. void Print(node *head)
  31. {
  32.     node *inc = head;
  33.     while (inc)
  34.     {
  35.         printf("%d", inc->data);
  36.         if (inc->next) printf(", ");
  37.         inc = inc->next;
  38.     }
  39.     putchar('\n');
  40. }
  41.  
  42. void Peek(node *head)
  43. {
  44.     if (head)
  45.         printf("%d\n", head->data);
  46. }
  47.  
  48. int main()
  49. {
  50.     node *stack = NULL;
  51.     int n;
  52.     printf("input stack: ");
  53.     while (1)
  54.     {
  55.         scanf("%d", &n);
  56.         if (n == -1) break;
  57.         stack = Push(stack, n);
  58.     }
  59.  
  60.     Print(stack);
  61.     printf("---Peek & Pop test---\n");
  62.     Peek(stack);
  63.     stack = Pop(stack);
  64.     Print(stack);
  65.  
  66.     _getch();
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment