链栈的置空入栈,出栈,和返回栈顶元素操作

#include "stdio.h"
#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;
}

你可能感兴趣的:(链表的头插尾插,插入修改和删除节点,链栈,C语言)