本文主要是介绍链栈的实现 c++ .,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
贴上自己的代码!!!!
#include <iostream>
using namespace std;
class LinkStack
{
public:
LinkStack()
{
top = NULL;
}
~LinkStack();
void Push(int x);
void Pop();
int GetTop() //取顶操作
{
if(top != NULL)
{
return top->data;
}
}
bool Empty() //判空操作
{
if(top == NULL)
return 1;
else
return 0;
}
LinkStack *next;
private:
LinkStack *top;
int data;
};
//链栈的入栈
void LinkStack::Push(int x)
{
LinkStack *s = new LinkStack;
s -> data = x;
s -> next = top;
top = s;
}
//链栈的出栈
void LinkStack::Pop()
{
LinkStack *p;
int x;
if(top == NULL)
cout<<"发生下溢!"<<endl;
while(top)
{
x = top -> data;
p = top;
top = top -> next;
cout << x << " ";
}
cout<<endl;
}
//释放链栈中所有结点的存储空间
LinkStack::~LinkStack()
{
LinkStack *p = new LinkStack;
while(top)
{
p = top -> next;
delete top;
top = p;
}
}
int main()
{
LinkStack Stack;
int n;
while(cin >> n, n)
{
Stack.Push(n);
}
int ss;
ss = Stack.GetTop();
cout << "栈顶元素为:";
cout << ss << endl;
int qq;
qq = Stack.Empty();
cout << "栈是否为空(0表示非空 1表示空):";
cout << qq << endl;
cout<<"出栈的元素为:";
Stack.Pop();
return 0;
}
贴上别人的代码!!
#include <iostream>
#include <string>
using namespace std;
struct Data
{
public:
int bookNum;
Data * next;
};
//链栈的初始化
Data* SeqStackInit()
{
Data *top = new Data;
top = NULL;
return top;
}
//链栈的判空
int SeqStackEmpty(Data* s)
{
if (NULL == s)
{
return true;
}
else
return false;
}
//链栈的入栈
Data * SeqStackPush(Data* s, int x)
{
Data* s1 = new Data;
s1->bookNum = x;
s1->next = s;
s = s1;
cout<<"入栈元素:"<<s->bookNum<<endl;
return s;
}
//链栈的出栈
Data * SeqStackPop(Data* s)
{
if (NULL != s)
{
int x;
Data * p = new Data;
p = s;
x = s->bookNum;
cout <<"出栈元素:"<<s->bookNum<<endl;
s = s->next;
delete(p);
return s;
}
}
//链栈中取出栈顶元素
int SeqStackGetTop(Data* s)
{
if (NULL != s)
return s->bookNum;
}
//链栈的长度
int SeqStackLength(Data* s)
{
int length = 0;
Data* s1 = s;
//cout <<s->bookNum<<endl;
while(NULL != s1)
{
length++;
s1 = s1->next;
}
return length;
}
int main()
{
Data* s = SeqStackInit();
cout <<"判空操作:"<<SeqStackEmpty(s)<<endl;
cout <<"入栈操作:"<<endl;
s = SeqStackPush(s,12);
s = SeqStackPush(s,23);
s = SeqStackPush(s,4);
s = SeqStackPush(s,78);
s = SeqStackPush(s,3);
cout <<"栈顶元素:"<<SeqStackGetTop(s)<<endl;
cout <<"栈的长度:"<<SeqStackLength(s)<<endl;
cout <<"出栈操作:"<<endl;
s = SeqStackPop(s);
cout <<"判空操作:"<<SeqStackEmpty(s)<<endl;
cout <<"栈的长度:"<<SeqStackLength(s)<<endl;
cout <<"栈顶元素:"<<SeqStackGetTop(s)<<endl;
return 0;
}
这篇关于链栈的实现 c++ .的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!