Create stack based on linked list - C Data Structure

C examples for Data Structure:Linked List

Description

Create stack based on linked list

Demo Code

#include <stdio.h>
#include <stdlib.h>

#define Error -9999//from  w  w  w .  j  a v  a 2 s.  c  om

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);
}

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

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

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 \n", pop(S));
}

Related Tutorials