栈的链式存储(包括栈的初始化,进栈,出栈,判空等等)
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct Linknode
{
ElemType data;
struct Linknode* next;
}*LiStack;
LiStack initLiStack(LiStack& S);
void printLiStack(LiStack& S);
LiStack AddLiStack(LiStack& S, int& n);
LiStack deleteLiStack(LiStack& S, int& n);
int main()
{
LiStack S;
int n = 0;
initLiStack(S);
AddLiStack(S, n);
printLiStack(S);
deleteLiStack(S,n);
printLiStack(S);
system("pause");
return 0;
}
//链栈初始化
LiStack initLiStack(LiStack &S)
{
S = NULL;
return S;
}
//增加栈中元素(进栈)
LiStack AddLiStack(LiStack& S,int &n)
{
LiStack p;
p = S;
ElemType e = 0;
int i;
cout << "请输入进栈元素个数:" << endl;
cin >> i;
cout << "请依次输入增加的元素:" << endl;
while (i!=0)
{
cin >> e;
p = new struct Linknode;
p->data = e;
if (S == NULL)
p->next = NULL;
else
p->next = S;
S = p;
i--;
n++;
}
cout << "进栈成功: " << endl;
return S;
}
//显示栈中元素
void printLiStack(LiStack& S)
{
LiStack q;
q = S;
if (q)
{
cout << "栈中的元素为:" << endl;
while (q)
{
cout << q->data << " ";
q = q->next;
}
cout << endl;
}
else
{
cout << "此链栈为空:" << endl;
}
}
//删除栈中元素(出栈)
LiStack deleteLiStack(LiStack& S,ElemType &n)
{
LiStack q;
cout << "请输入出栈元素个数:" << endl;
int i;
cin >> i;
while (i>n)
{
cout << "输入数据有误,请输入小于等于栈中元素个数" << n << "的值" << endl;
cin >> i;
}
while (i != 0)
{
q = S;
S = S->next;
delete q;
q = NULL;
i--;
n--;
}
cout << "出栈成功:" << endl;
return S;
}
bool IsEmptyListack(LiStack& S)
{
if (S == NULL)
return false;
else
return true;
}