#include<stdio.h>
#include<stdlib.h>
typedef struct stacknode
{
char data;
struct stacknode *next;
}stacknode;
stacknode* creat_stack()
{
stacknode *top = NULL;
return top;
}
stacknode* push(stacknode *top, char data)
{
stacknode *p = (stacknode *)malloc(sizeof(stacknode));
p->data = data;
p->next = top;
top = p;
return top;
}
stacknode* pop(stacknode *top, char *t)
{
stacknode *p = NULL;
if (top == NULL)
{
printf("栈为空,无法出栈!\n");
return NULL;
}
*t = top->data;
p = top;
top = top->next;
printf("元素%c已出栈\n", *t);
free(p);
return top;
}
void output(stacknode *top)
{
if (top == NULL)
printf("栈为空\n");
else
{
stacknode *p = (stacknode *)malloc(sizeof(stacknode));
p = top;
printf("栈遍历为:");
while(p != NULL)
{
printf("%c ", p->data);
p = p->next;
}
free(p);
printf("\n");
}
}
void Node_count(stacknode *top)
{
int count = 0;
stacknode *temp = top;
while(temp != NULL)
{
count++;
temp = temp->next;
}
printf("栈的结点个数为%d\n", count);
}
stacknode* Destroy_stack(stacknode *top)
{
if(top == NULL)
printf("栈为空,无法销毁!\n");
else
{
stacknode *temp;
while(top != NULL)
{
temp = top->next;
free(top);
top = temp;
}
printf("栈已销毁!\n");
}
return NULL;
}
int main()
{
stacknode *top = creat_stack();
printf(" 栈子系统\n");
printf("**************************************************\n");
printf("* 1-----入栈 *\n");
printf("* 2-----出栈 *\n");
printf("* 3-----显示栈 *\n");
printf("* 4-----求栈的结点个数 *\n");
printf("* 5-----销毁栈 *\n");
printf("* 0-----结束 *\n");
printf("**************************************************\n");
while (1)
{
int ch;
printf("\n***************************************************\n");
printf("请输入你要进行的操作对应的数字:");
scanf("%d",&ch);
getchar();
switch(ch)
{
case 1:
{
char data;
printf("请输入要入栈的元素:");
scanf("%c", &data);
getchar();
top = push(top, data);
printf("元素%c已入栈\n", data);
break;
}
case 2:
{
char t = 0;
top = pop(top, &t);
break;
}
case 3:
{
output(top);
break;
}
case 4:
{
Node_count(top);
break;
}
case 5:
{
top = Destroy_stack(top);
break;
}
case 0:
{
printf("程序已结束!\n");
return 0;
}
default:
{
printf("输入的数值有误,请重新输入\n");
break;
}
}
}
return 0;
}