数据结构线性表 - 链栈练习Demo
链栈相对于顺序栈来说更加灵活,不存在栈满的问题,但是实现起来比顺序栈稍微麻烦一点,因为栈主要的操作就是出栈和入栈操作,作为链栈的练习,我也只写了出栈和入栈还有查看链栈数据这几个功能。代码写完测试完感觉没啥问题。直接上代码。
#include <iostream>
using namespace std;
typedef struct{
char p;
}Elem;
typedef struct SNode{
Elem data;
struct SNode *next;
}SNode,*LinkStack;
int flag = 1;
void InitStack(LinkStack &L, LinkStack &H)
{
L = NULL;
H = L;
cout << "初始化成功!";
}
void Push(LinkStack &L,LinkStack &H)
{
char k;
LinkStack p;
cout << "输入入栈的数据:";
cin >> k;
if (H == L)
{
L = new SNode;
L->data.p = k;
L->next = NULL;
H = L;
}
p = new SNode;
p->data.p = k;
p->next = H;
H = p;
flag = 0;
}
void Push_All(LinkStack &L, LinkStack &H)
{
char k='NULL';
cout << "输入入栈的数据(#结束!):";
while (k != '#')
{
cin >> k;
if (k = '#')
{
return;
}
if (H == L)
{
L = new SNode;
L->data.p = k;
L->next = NULL;
H = L;
}
LinkStack p;
p = new SNode;
p->data.p = k;
p->next = H;
H = p;
flag = 0;
}
}
void Pop(LinkStack &L, LinkStack &H)
{
if (flag == 1)
{
cout << "链栈没有数据,无法弹出数据!";
return;
}
if (H == L)
{
cout << H->data.p << "弹出栈!!";
flag = 1;
}
else
{
LinkStack p;
p = H;
H = H->next;
cout << p->data.p << "弹出栈!";
delete p;
}
}
void print_Stack(LinkStack &L, LinkStack &H)
{
LinkStack p;
p = H;
while (p->next != NULL)
{
cout << p->data.p;
p = p->next;
}
}
void Contents() //菜单清单
{
cout << "*********************************\n";
cout << "* 链 栈 练 习 *\n";
cout << "* *\n";
cout << "* 1.初始化链栈 *\n";
cout << "* 2.数据入栈 *\n";
cout << "* 3.数据出栈 *\n";
cout << "* 4.查看链栈中的数据 *\n";
cout << "* 5.退出程序 *\n";
cout << "*********************************\n";
}
void main()
{
LinkStack L,H;
int a;
Contents();
while (1)
{
system("cls");
Contents();
cout << "请选择功能:";
cin >> a;
switch (a)
{
case 1: InitStack(L, H); system("PAUSE"); break;
case 2: Push(L, H); system("PAUSE"); break;
case 3: Pop(L, H); system("PAUSE"); break;
case 4: print_Stack(L, H); system("PAUSE"); break;
case 5:exit(-1);
default: printf("输入错误!请重新输入"); system("PAUSE"); break;
}
}
}
栈的知识主要在顺序栈说了,想要初步了解的可以看看我的上一篇顺序栈的帖子。一起学习,,加油!