linkstack.h
#ifndef __LINKSTACK_H__
#define __LINKSTACK_H__
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node{
datatype data;
struct node *next;
}stacknode,*linkstack;
linkstack create_linkstack(void);
void clear_linkstack(linkstack L);
void free_linkstack(linkstack L);
int is_empty_linkstack(linkstack L);
int push_linkstack(linkstack L,datatype x);
datatype pop_linkstack(linkstack L);
datatype get_top_linkstack(linkstack L);
void show_linkstack(linkstack L);
#endif
linkstack.c
#include "linkstack.h"
linkstack create_linkstack(void)
{
linkstack H;
if((H = (linkstack)malloc(sizeof(stacknode))) == NULL)
{
printf("malloc no memory!\n");
return NULL;
}
H->data = 0;
H->next = NULL;
return H;
}
void clear_linkstack(linkstack L)
{
linkstack r;
r = L->next;
while(r != NULL)
{
L->next = r->next;
r->next = NULL;
free(r);
r = L->next;
}
}
void free_linkstack(linkstack L)
{
linkstack r;
r = L;
while(!is_empty_linkstack(L))
{
L = r->next;
r->next =NULL;
free(r);
r = L;
}
}
int is_empty_linkstack(linkstack L)
{
return (L->next == NULL);
}
int push_linkstack(linkstack L,datatype x)
{
linkstack H,r;
r = L;
if((H = (linkstack)malloc(sizeof(stacknode))) == NULL)
{
printf("malloc no memory!\n");
return -1;
}
H->data = x;
H->next = r->next;
r->next = H;
return 0;
}
datatype pop_linkstack(linkstack L)
{
datatype x;
linkstack r;
if(is_empty_linkstack(L))
{
printf("stack is NULL!\n");
return -1;
}
r = L->next;
L->next = r->next;
r->next = NULL;
x = r->data;
free(r);
r = NULL;
return x;
}
datatype get_top_linkstack(linkstack L)
{
if(is_empty_linkstack(L))
{
printf("stack is NULL!\n");
return -1;
}
return (L->next->data);
}
void show_linkstack(linkstack L)
{
while(!is_empty_linkstack(L))
{
printf("%d\t",pop_linkstack(L));
}
puts("");
}
main.c
#include "linkstack.h"
int main(int argc, const char *argv[])
{
linkstack H;
H = create_linkstack();
push_linkstack(H,10);
push_linkstack(H,20);
push_linkstack(H,30);
push_linkstack(H,40);
push_linkstack(H,50);
show_linkstack(H);
free_linkstack(H);
return 0;
}
运行结果