首页 > 数据结构 > 阅读:57,774

基于链表的栈

现在来实现基于链表的栈的常规操作。(注意,在多线程环境下,下面的代码没有提供加锁机制,需要另外处理)。

 

 

先定义栈的结点结构:

typedef struct _node

{

       int value;

       struct _node *next;

}node,*pnode;

栈顶指针初始化:

node *top = NULL;

 

创建栈:

int CreateStack()

{

       top = NULL;

       return 1;

}

 

判断栈是否为空:

int IsStackEmpty()

{

       return top==NULL?1:0;//topNULL的时候,栈为空

}

入栈:

int Push(int value)

{

       node *p = (node *)malloc(sizeof(node));

       if(p==NULL)

       {

              return -1;

       }

       memset(p,0,sizeof(node));

       p->value=value;

       p->next=NULL;

 

       //栈为空的时候,插入的是第一个结点

       if(IsStackEmpty())

       {

              top=p;

              return 1;

       }

 

       //栈非空的时候,插入一个结点

       p->next = top;

       top=p;

 

       return 1;

 

}

出栈

int Pop(int *e)

{

       if(IsStackEmpty())

       {

              return -1;

       }

       if(e==NULL)

       {

              return -1;

       }

 

       //当栈只有一个结点的时候:

       if(top->next==NULL)

       {

              *e = top->value;

              free(top);

              top=NULL;

              return 1;

       }

 

       //当栈中存放不止一个元素的时候

       *e = top->value;

       node *p=top;

       top=top->next;

       free(p);

 

       return 1;

 

}

栈的遍历:

void TraverseStack()

{

       while(!IsStackEmpty())

       {

              int val;

              Pop(&val);

              printf("%d ", val);

      

       }

       printf("\n");

}

 

接口测试:

int _tmain(int argc, _TCHAR* argv[])

{

       CreateStack();

 

       for(int i=0;i<100;i++)

       {

              Push(i+1);

       }

       int val;

       Pop(&val);

       printf("val:%d\n", val);

 

       TraverseStack();

 

       return 0;

}

周哥教IT,分享编程知识,提高编程技能,程序员的充电站。跟着周哥一起学习,每天都有进步。

通俗易懂,深入浅出,一篇文章只讲一个知识点。

当你决定关注「周哥教IT」,你已然超越了90%的程序员!

IT黄埔-周哥教IT技术交流QQ群:213774841,期待您的加入!

二维码
微信扫描二维码关注