C 实现简单的栈

加班无聊,没事就写了一个简单栈,该源代码包含一个stk.h和stk.c

 具体实现如下

  

stk.h

 

typedef unsigned int uint;
typedef struct _node
{
void *data;
uint size;
struct _node *down;
}__attribute__((packed)) node;
typedef struct _stk
{
struct _node *top;
uint len;
}__attribute__((packed)) stk;
/* init stk */
stk *stk_new();
/* push one data into stk */
int stk_push(stk *root,void *data,uint size);
/* pop one element out of stk */
int stk_pop(stk *root);
/* get size of stk */
int stk_size(stk *root);
/* destroy stk */
int stk_destroy(stk *root);
/* print all data */
int stk_prt(stk *root);

 

stk.c

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stk.h"
stk *stk_new()
{
stk *root=(stk *)malloc(sizeof(stk));
if(!root){fprintf(stderr,"stk fail to create
");return NULL;}
root->top=NULL;
root->len=0;
return root;
}
int stk_push(stk *root,void *data,uint size)
{
node *n=(node *)malloc(sizeof(node));
if(!root||!n){fprintf(stderr,"node fail to create or stk is null
");return 1;}
n->data=malloc(size);
if(!n->data){fprintf(stderr,"n->data fail to create
");return 1;}
memset(n->data,0,size);
memcpy((char *)n->data,data,size);
n->size=size;
n->down=root->top;
root->top=n;
root->len++;
return 0;
}
int stk_empty(stk *root)
{
if(!root){fprintf(stderr," stk root is null
");return -1;}
if(root->len>=1){return 1;}
return 0;
}
int stk_pop(stk *root)
{
if(!root){fprintf(stderr,"stk root is null
");return 1;}
node *p=root->top;
root->top=p->down;
root->len--;
free(p);
printf("	 free node:%p
",p);
return 0;
}
int stk_size(stk *root)
{
if(!root){fprintf(stderr,"stk root is null
");return 0;}
return root->len;
}
int stk_destroy(stk *root)
{
if(!root){fprintf(stderr," stk root is null
");return 1;}
node *pnode=root->top;
while(pnode)
{
printf("node =%p free ",pnode);
node *tmp=pnode->down;
free(pnode);
pnode=tmp;
root->len--;
printf(" ok!
");
}
root->top=NULL;
}
int stk_prt(stk *root)
{
if(!root){fprintf(stderr," stk root is null
");return 1;}
node *pnode=root->top;
printf("	 root->len:%d
",root->len);
while(pnode!=NULL)
{
printf(" pnode = %p,pnode->down =%p,pnode->size=%d
",pnode,pnode->down,pnode->size);
printf(" pnode->data:%s
",(char *)pnode->data);
pnode=pnode->down;
}
return 0;
}
int main(void)
{
stk *p=stk_new();
char *v1="hello word";
char * vp1="200";
char *s1="c programing";
char *c="FBI";
printf("stk_push(%s):%d
",v1,stk_push(p,v1,strlen(v1)+1));
printf("stk_push(%s):%d
",vp1,stk_push(p,vp1,strlen(vp1)+1));
printf("stk_push(%s):%d
",s1,stk_push(p,s1,strlen(s1)+1));
printf("stk_push(%s):%d
",c,stk_push(p,c,strlen(c)+1));
stk_prt(p);
printf("####################################
");
printf("stk_size :%d
",stk_size(p));
printf("stk_pop :%d
",stk_pop(p));
stk_prt(p);
printf("stk_size :%d
",stk_size(p));
stk_destroy(p);
stk_prt(p);
return 0;
}

 

  代码写的比较差,请阅读者多提宝贵建议,嘻嘻。

原文地址:https://www.cnblogs.com/innobase/p/4504507.html