#include <stdio.h>
#include <stdlib.h>
typedef char DataType ;
struct node;//定義一個結點
typedef struct node *PNode; //定義結點指針
struct node{
DataType info;
PNode next;
};
struct stack{//創建一個棧結構體
PNode top;//指向棧頂元素
};
typedef struct stack *Pointstack;
Pointstack createEmpty_stack(void);//無返回值
int ifEmpty_stack(Pointstack Pstack);//傳入棧參數
void pushElement_stack(Pointstack pstack,DataType x);
void popElement_stack(Pointstack pstack,DataType x);
DataType ElementStackTop(Pointstack pstack);
//創建一個空棧,返回指向空棧的指針
Pointstack createEmpty_stack(){
Pointstack Pstack=(Pointstack)malloc(sizeof(struct stack));//爲結點申請空間
if(Pstack!=NULL){
Pstack->top=NULL;//棧頂賦值爲空
}
else{
printf("out of speac");
}
return Pstack;
}
//判斷棧是否爲空
int ifEmpty_stack(Pointstack pstack){
return (pstack->top?0:1);
}
//往棧中壓入一個元素
void pushElement_stack(Pointstack pstack,DataType x){
PNode Snode=(PNode)malloc(sizeof(struct node));//申請一個新的結點空間
if (Snode==NULL)
{
printf("out of speac");
}
else
{
Snode->info=x;
Snode->next=pstack->top;
pstack->top=Snode;
}
//printf("進棧成功\n");
}
//出棧。即刪除一個元素
void popElement_stack(Pointstack pstack){
if (ifEmpty_stack(pstack))//判斷棧是否已空
{
printf("out of speac");
}
else
{
PNode p=pstack->top;
pstack->top=pstack->top->next;
free(p);
}
}
//求棧頂元素
DataType ElementStackTop(Pointstack pstack){
if (ifEmpty_stack(pstack))
{
printf("stack is empty\n");
exit(0);
}
else
{
return pstack->top->info;
}
}
void main(){
int data;
char ch;
int top;
Pointstack newstack=createEmpty_stack();
printf("輸入數字創建棧,以-1結束輸入:\n");
scanf("%d",&data);
while(data!=-1){
pushElement_stack(newstack,data);
scanf("%d",&data);
}
printf("\n");
while(!ifEmpty_stack(newstack)){
top=ElementStackTop(newstack);
printf("%d ",top);
popElement_stack(newstack);
}
}
數據結構C 語言描述——實現棧的基本功能
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.