考研学习—数据结构—链栈
作者:
sshixx
,
2022-07-31 10:13:30
,
所有人可见
,
阅读 184
链栈的基本操作
有问题欢迎大家指出
#include <iostream>
using namespace std;
typedef struct SNode
{
int data;
struct SNode *next;
SNode(): next(NULL) {}
SNode(int _data):data(_data),next(NULL){}
} *LinkStack;
void InitStack(LinkStack &s)
{
s = new SNode(-1);
s->next = NULL;
}
bool StackEmpty(LinkStack s)
{
if(s->next == NULL) return true;
return false;
}
void PushStack(LinkStack &s, int e)
{
SNode *p = new SNode(e);
SNode *top = s;
p->next = top->next;
top->next = p;
}
void PopStack(LinkStack &s)
{
if(!StackEmpty(s))
{
SNode *p = s->next;
s->next = p->next;
cout << p->data << endl;
delete(p);
}
}
int StcakLength(LinkStack s)
{
int length = 0;
SNode *p = s->next;
while(p)
{
length ++;
p = p->next;
}
return length;
}
void Output(LinkStack s)
{
SNode *p = s->next;
while(p)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main()
{
LinkStack s;
InitStack(s);
for(int i = 0; i < 10; i ++)
PushStack(s, i);
cout << StcakLength(s);
cout << "---------------" << endl;
Output(s);
PushStack(s, 100);
Output(s);
PopStack(s);
PopStack(s);PopStack(s);PopStack(s);PopStack(s);PopStack(s);PopStack(s);
PopStack(s);PopStack(s);PopStack(s);PopStack(s);
cout << StcakLength(s);
cout << "---------------" << endl;
if(StackEmpty(s))
cout << "k" << endl;
else
cout << "bk" << endl;
return 0;
}