加班无聊,没事就写了一个简单栈,该源代码包含一个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\n");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\n");return 1;}
n->data=malloc(size);
if(!n->data){fprintf(stderr,"n->data fail to create\n");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\n");return -1;}
if(root->len>=1){return 1;}
return 0;
}
int stk_pop(stk *root)
{
if(!root){fprintf(stderr,"stk root is null\n");return 1;}
node *p=root->top;
root->top=p->down;
root->len--;
free(p);
printf("\t free node:%p\n",p);
return 0;
}
int stk_size(stk *root)
{
if(!root){fprintf(stderr,"stk root is null\n");return 0;}
return root->len;
}
int stk_destroy(stk *root)
{
if(!root){fprintf(stderr," stk root is null\n");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!\n");
}
root->top=NULL;
}
int stk_prt(stk *root)
{
if(!root){fprintf(stderr," stk root is null\n");return 1;}
node *pnode=root->top;
printf("\t root->len:%d\n",root->len);
while(pnode!=NULL)
{
printf(" pnode = %p,pnode->down =%p,pnode->size=%d\n",pnode,pnode->down,pnode->size);
printf(" pnode->data:%s\n",(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\n",v1,stk_push(p,v1,strlen(v1)+1));
printf("stk_push(%s):%d\n",vp1,stk_push(p,vp1,strlen(vp1)+1));
printf("stk_push(%s):%d\n",s1,stk_push(p,s1,strlen(s1)+1));
printf("stk_push(%s):%d\n",c,stk_push(p,c,strlen(c)+1));
stk_prt(p);
printf("####################################\n");
printf("stk_size :%d\n",stk_size(p));
printf("stk_pop :%d\n",stk_pop(p));
stk_prt(p);
printf("stk_size :%d\n",stk_size(p));
stk_destroy(p);
stk_prt(p);
return 0;
}

 

 

 

 

 

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

 

版权声明:本文为innobase原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/innobase/p/4504507.html