Code
/*
InitStack(&S):初始化一个空栈S。
StackEmpty(S):判断一个栈是否为空,若栈为空则返回true,否则返回false。
Push(&S, x):进栈,若栈S未满,则将x加入使之成为新栈顶。
Pop(&S, &x):出栈,若栈非空,则弹出栈顶元素,并用x返回。
GetTop(S, &x):读栈顶元素,若栈非空则用x返回栈顶元素。
ClearStack(&S):销毁栈,并释放S占用的内存空间。
* */
#include <iostream>
using namespace std;
#define ElemType int
//栈链式存储数据结构//
typedef struct Linknode{
ElemType data;
struct Linknode *next;
}*LiStack ;
//创建栈头节点 所有操作只能在头部操作//
LiStack CreatHeader(){
Linknode* head=(Linknode*)malloc(sizeof(Linknode));
if(head==NULL){
cout<<"内存不够申请"<<endl;
}
head->data=0;
head->next=NULL;
return head;
}
//入栈//
void Push(LiStack &head , ElemType x){
if(head==NULL){
cout<<"ERROR"<<endl;
return;
}
//为入栈的元素申请一个节点
Linknode* node=(Linknode*)malloc(sizeof(Linknode));
if(node==NULL){
cout<<"内存不足申请"<<endl;
return ;
}
node->data=x;
node->next=head->next;
head->next=node;
}
//出栈操作//
ElemType Pop(LiStack &head,ElemType &x){
if(head==NULL || head->next==NULL){
cout<<"ERROR"<<endl;
return -1;
}
Linknode* temp=head->next;
head->next=temp->next;
x=temp->data;
return x;
}
//获取栈的元素个数//
int GetLength(LiStack head){
if(head==NULL || head->next==NULL){
return 0;
}
int len=0;
Linknode* p=head->next;
while(p!=NULL){
len++;
p=p->next;
}
return len;
}
//遍历操作//
void Traversal(LiStack head){
if(head==NULL || head->next==NULL){
cout<<"NO"<<endl;
return;
}
Linknode* p=head->next;
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main(){
LiStack head=CreatHeader();
Push(head,1);
Push(head,5);
Push(head,8);
cout<<"遍历结果"<<endl;
Traversal(head);
cout<<"当前栈长度"<<GetLength(head)<<endl;
int x;
cout<<Pop(head,x)<<endl;
cout<<"遍历结果"<<endl;
Traversal(head);
cout<<"当前栈长度"<<GetLength(head)<<endl;
return 0;
}
Input && Ouput
遍历结果
8 5 1
当前栈长度3
8
遍历结果
5 1
当前栈长度2
Process finished with exit code 0