C Program For Implementing a Stack Using a Linked List

/*Implementing a Stack Using a Linked List*/
/* To read some numbers and print them in reverse order. For example, say we have these numbers:
36 15 52 23
And say we want to print the following:
23 52 15 36 */
#include <stdio.h>
#include <stdlib.h>
#define RogueValue -9999
typedef struct node {
   int num;
   struct node *next;
} Node, *NodePtr;

typedef struct stackType {
      NodePtr top;
} StackType, *Stack;

Stack initStack() {
      Stack sp = (Stack) malloc(sizeof(StackType));
      sp -> top = NULL;
      return sp;
}
int empty(Stack S) {
      return (S -> top == NULL);
} //end empty

void push(Stack S, int n) {
      NodePtr np = (NodePtr) malloc(sizeof(Node));
      np -> num = n;
      np -> next = S -> top;
      S -> top = np;
} //end push

int pop(Stack S) {
      if (empty(S)) return RogueValue;
      int hold = S -> top -> num;
      NodePtr temp = S -> top;
      S -> top = S -> top -> next;
      free(temp);
      return hold;
} //end pop

int main() {
      int n;
      Stack S = initStack();
      printf("Enter some integers, ending with 0\n");
      scanf("%d", &n);
      while (n != 0) {
            push(S, n);
            scanf("%d", &n);
      }
      printf("\nNumbers in reverse order\n");
      while (!empty(S))
            printf("%d ", pop(S));
      printf("\n");
}
Bhanu Namikaze

Bhanu Namikaze is an Ethical Hacker, Security Analyst, Blogger, Web Developer and a Mechanical Engineer. He Enjoys writing articles, Blogging, Debugging Errors and Capture the Flags. Enjoy Learning; There is Nothing Like Absolute Defeat - Try and try until you Succeed.

No comments:

Post a Comment