鏈棧的置空入棧,出棧,和返回棧頂元素操作
#include "stdlib.h"
#define N sizeof(struct stack)
typedef struct stack{
int data;
struct stack *next;
}*pstack;
//置空鏈棧
pstack empty(pstack top){
top = NULL;
printf("棧已經置空!\n");
return top;
}
//判斷棧空
void isempty(pstack top){
if (top == NULL)
printf("鏈棧為空!\n");
else
printf("鏈棧不為空!\n");
}
//入鏈棧
pstack push(pstack top){
pstack p;
int k;
p = (pstack)malloc(N);
printf("請輸入你想插入的資料:");
scanf("%d",&p->data);
p->next = top;
top = p;
return top;
}
//出鏈棧
pstack pop(pstack top){
pstack p;
if (top != NULL)
{
p = (pstack)malloc(N);
p = top;
top = top->next;
free(p);
}
else
printf("棧是空的,無法出棧!\n");
printf("出棧操作已完成!\n");
return top;
}
//返回棧頂元素
pstack getstacktop(pstack top){
return top;
}
//主函式
int main()
{
pstack top;
int n;
top = NULL;
do{
printf("***********************\n");
printf("* 1.置空鏈棧\n* 2.判斷鏈棧是否為空\n* 3.進棧操作\n* 4.出棧操作\n* 5.返回棧頂數字\n* 6.退出程式\n");
printf("***********************\n");
printf("請輸入你的選擇:\n");
scanf("%d",&n);
switch (n){
case 1:
empty(top);
break;
case 2:
isempty(top);
break;
case 3:
top=push(top);
break;
case 4:
top=pop(top);
break;
case 5:
if (top != NULL)
printf("棧頂元素是:%d\n", getstacktop(top)->data);
else
printf("棧為空!\n");
case 6:
break;
default:
printf("請輸入正確的選擇:\n");
}
} while (n!=6);
printf("程式已經結束!\n");
return 0;
}