This is a another version of stack data structure implementation using link representation. With this version the stack size is dynamic and determined at run-time.
linkedstack.c (0.5 KB) linkedstack.c | |
linkedstack.h (0.5 KB) Header file of linked stack | |
testlinkedstack.c (0.7 KB) testlinkedstack.c |
linkedstack.h
int empty(struct node *s);
struct node* push(struct node *s,int data);
struct node* pop(struct node *s,int *data);
void init(struct node* s);
linkedstack.c
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
void init(struct node* s){
s = NULL;
}
struct node* push(struct node* s,int data)
{
struct node* tmp = (struct node*)malloc(sizeof(struct node));
if(tmp == NULL){
// no memory available
exit(0);
}
tmp->data = data;
tmp->next = s;
s = tmp;
return s;
}
struct node* pop(struct node *s,int *element)
{
struct node* tmp = s;
*element = s->data;
s = s->next;
free(tmp);
return s;
}
int empty(struct node* s){
return s == NULL ? 1 : 0;
}
linkedstack.c
#include <stdio.h>
#include <stdlib.h>
#include "linkedstack.h"
void main()
{
struct node* head = NULL;
int size,element,counter = 0;
/* stack size is dynamic and
specified at runtime */
printf("Enter stack size:");
scanf("%d",&size);
printf("Push elements to stack\n");
init(head);
while(counter < size)
{
getchar();
element = rand();
printf("push element %d into stack\n",element);
head = push(head,element);
counter++;
}
printf("Pop elements from stack\n");
while(0 == empty(head))
{
head = pop(head,&element);
printf("pop element %d from stack\n",element);
getchar();
}
getchar();
}
0 comments:
Post a Comment