链式堆栈——C语言实现

来源:互联网 发布:英国综合国力知乎 编辑:程序博客网 时间:2024/05/06 05:10

链式栈具有存储灵活,没存利用率高的特点,今天采用c语言实现链式堆栈。栈的主体采用单链表的方式实现,链表不带头结点。为了方便知道栈的栈底和栈顶,需要定义两个分别指向链表的头和尾的指针top,base。链表从头部生长,出栈也从头部出,这样实现起来比较简单。
进栈出栈的图示如下:
链式栈
链表的数据结构:

#define OK 0#define ERROR 1typedef int SElemType;/*声明栈的数据结构*/typedef struct node{   SElemType data;   struct node *next;}LsNode;typedef struct{   LsNode *base;//栈底指针   LsNode *top;//栈顶指针   int stackSize;//栈的当前容量}LStack;

功能函数:

#include<stdio.h>#include<stdlib.h>#include"stack.h"#include<malloc.h>/*功能:创建一个栈  返回:返回指向栈的指针  */LStack *Create_LsStack(){    LStack *S;    S=(LStack *)malloc(sizeof(LStack));    S->top=S->base=(LsNode *)malloc(sizeof(LsNode));    if(!S->base)    {       printf("no memory aviable\n");       exit(0);    }    S->base->next=NULL;    S->stackSize=0;    return S;}/*功能:元素进栈  返回:OK:进栈成功        ERROR:进栈失败        OVERFLOW:溢出  */int Push_SqStack(LStack *S,SElemType e){    LsNode *NewNode;    NewNode=(LsNode *)malloc(sizeof(LsNode));    if(NewNode==NULL)    {        printf("there is not enough memory aviable\n");        return ERROR;    }    NewNode->data=e;    if(S->stackSize==0)//第一个进栈的节点需要特殊处理    {      S->top->data=e;      S->base->next=NULL;      S->stackSize++;      free(NewNode);    }    else     {        NewNode->next=S->top;        S->top=NewNode;        S->stackSize++;    }    return OK;}/*功能:元素出栈  返回:栈顶的值  */SElemType Pop_LsStack(LStack *S){    LsNode *p;    SElemType e;    if(S->stackSize==0)    {        printf("stack is empty\n");        return ERROR;    }    else    {        p=S->top;        e=p->data;        S->top=S->top->next;    //  p->next=NULL;        free(p);        return e;    }}/*功能:读取栈顶的元素  返回:栈顶元素的值  */SElemType Read_Top_LsStack(LStack *S){    SElemType top;   if(S->stackSize==0)    {        printf("stack is empty\n");        return ERROR;    }   top=S->top->data;   return top;}

实现功能,将9个数一次压入堆栈,从其中读出5个,返回剩下堆栈的栈顶指针。

#include<stdio.h>#include<stdlib.h>#include<malloc.h>#include"stack.h"int main(void){ LStack *S;    int i;    SElemType x,result;    printf("创建一个链式的栈\n");    S=Create_LsStack();    if(S!=NULL)printf("创建成功\n");    printf("进栈的元素为:\n");    for(i=1;i<10;i++)    {      result=Push_SqStack(S, i);      if(result==OK)printf("%d\t",i);    }    printf("\n");    printf("出栈的元素为\n");    for(i=0;i<5;i++)    {       x=Pop_LsStack(S);       printf("%d\t",x);    }    printf("\n");    printf("栈顶的元素为\n");    x=Read_Top_LsStack(S);    printf("%d\n",x);     system("pause");    return 0;}

运行结果:
这里写图片描述

0 0