@【数据结构】(链栈 基本函数)
链栈基本函数定义:进栈,出栈,取栈顶元素,判栈空,输出栈内元素
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
typedef int datatype;
typedef struct node
{
datatype data;
struct node *next;
}StackNode, *LinkStack;
using namespace std;
LinkStack Init() //置空栈
{
return NULL;
}
int Empty(LinkStack top)
{
if (top == NULL) return 1;
else return 0;
}
int Gettop(LinkStack top, datatype &x)
{
StackNode *s = top;
if (s == NULL) return 0;
else
{
x = s->data;
return x;
}
}
LinkStack push(LinkStack top, datatype x)
{
StackNode *s;
s = (StackNode*)malloc(sizeof(StackNode));
s->data = x;
s->next = top; top = s; //新结点插入链表
return top;
}
LinkStack pop(LinkStack top, datatype *x)
{
StackNode *s;
if (top== NULL) return(NULL); //空栈,返回空
else
{
*x = top->data; s = top;
top = top->next; free(s);
return top; //返回原栈顶结点数据域的值
}
}
void OutputLinkstack(LinkStack top)
{
StackNode *s;
s = top;
while(s!=NULL)
{
cout << s->data << " ";
s=s->next;
}
cout << endl;
}
void main()
{
LinkStack top;
top=Init();
top=push(top, 1);
top=push(top, 4);
top=push(top, 3);
top=push(top, 7);
top=push(top, 9);
cout << "初始时栈为:" << endl;
OutputLinkstack(top);
datatype x;
int index;
while (1) //永真循环
{
cout << "---------------------------------------------" << endl;
cout << "请选择操作:1:进栈" << endl;
cout << " 2:出栈 " << endl;
cout << " 3:获取栈顶元素 " << endl;
cout << " 4:栈是否为空 " << endl;
cout << " 5:输出栈内元素" << endl;
cout << " 0:退出 " << endl;
cout << "---------------------------------------------" << endl;
cin >> index;
switch (index)
{
case 1:
{
cout << "请输入x:";
cin >> x;
top=push(top, x); cout << x << "进栈后:";
OutputLinkstack(top); break;
}
case 2:
{
top=pop(top,&x);
cout <<x<< "出栈后:" << endl;
OutputLinkstack(top); break;
}
case 3:
{
cout << "栈顶元素为:" << Gettop(top,x)<<endl;
break;
}
case 4:
{
cout << "栈空情况(1为空,0为非空):" << Empty(top) << endl;
break;
}
case 5:
{
cout << "输出栈中元素:" << endl;
OutputLinkstack(top); break;
}
case 0: break;
}
}
system("pause");
}
测试示例:
进栈:
出栈:
判栈空:
…