栈的链式存储实现c语言

栈的链式存储

栈的基本操作c语言实现

#include<stdio.h>
#include<malloc.h>
using namespace std;
typedef int ElemType;
typedef struct StackNode{   //结点定义
ElemType data;
struct StackNode *next;
}StackNode,*LinkStack;
typedef struct Stack{
StackNode *Head;  // LinkStack Head;
StackNode *top;   // LinkStack top; 
    int count;
}Stack;
bool InitStack(Stack &S)               //构造一个空栈初始一结点
{
S.top=(LinkStack)malloc(sizeof(StackNode)); 
if(!S.top) return false;
S.top->next=NULL;
S.Head=S.top;
S.count=0;
return true;
}
int GetNumber(Stack S)
{
return S.count;  //返回栈中元素个数
}
void ClearStack(Stack &S)  //清空栈
{
LinkStack p=S.Head->next,q;
    while (p!=NULL) 
{
q=p;
p=p->next;       
free(q);
    }             //循环一次则将p指向的结点前一结点释放
S.top=S.Head;
S.Head->next=NULL;  
S.count=0;    
}
bool GetTop(Stack S,ElemType &elem)
{
if(S.count!=0)
{
elem=S.top->data;
return true;
}
else return false;
}
bool EmptyStack(Stack S)
{
if(S.count==0) return false;
else return true;
}
bool Push(Stack &S,ElemType elem)  //出栈
{
LinkStack s=(LinkStack)malloc(sizeof(StackNode)); //创造一个结点
if(!s) return false;
s->next=NULL;
s->data=elem;
S.top->next=s;
S.top=S.top->next;
S.count++;
return true;
}
bool Pop(Stack &S,ElemType &elem) //进栈
{
int j=1;
LinkStack p=S.Head;
while(j<S.count)
{
p=p->next;
j++;           //跳出循环为栈顶结点的前一结点
}
p->next=NULL;
elem=S.top->data;
free(S.top);   //释放栈顶结点
S.top=p;
S.count--;
return true;
}
void StackTraverse(Stack S)  //栈的遍历
{
LinkStack p=S.Head->next;
if(p==NULL) printf("栈空");
while (p!=NULL) 
{
printf("%3d",p->data);
p=p->next;
    } //跳出循环p指向栈顶结点
    printf("\n");
}
int main()
{
int elem1=1;
int elem2=2;
int elem3=3;
int temp=0;
Stack S;
InitStack(S);
Push(S,elem1);
Push(S,elem2);
Push(S,elem3);
printf("插入栈的顺序为");
StackTraverse(S);
Pop(S,temp);
printf("出栈:%i\n",temp);
printf("操作出栈一次后");
StackTraverse(S);
ClearStack(S);     //  清空栈 
StackTraverse(S);
return 0;
}

猜你喜欢

转载自blog.csdn.net/lin1094201572/article/details/78730527