#include<iostream>
using namespace std;
struct People
{
int id;
string name;
int age;
};
template <class Element>
struct Node
{
Element data;
Node<Element>* next;
};
template <class Element>
class LinkStack
{
public:
LinkStack();
~LinkStack();
void push(Element x);
Element pop();
Element getTop();
bool ifEmpty();
void menu();
private:
Node<Element>* top;
};
template <class Element>
LinkStack<Element>::LinkStack()
{
top = nullptr;
}
template <class Element>
LinkStack<Element>::~LinkStack()
{
Node<Element>* p=top;
while (top)
{
top = top->next;
delete p;
p = top;
}
}
template <class Element>
void LinkStack<Element>::push(Element x)
{
Node<Element>* s = new Node<Element>;
s->data = x;
s->next = top;
top = s;
}
template <class Element>
Element LinkStack<Element>::pop()
{
Node<Element>* p = top;
Element x = p->data;
top = top->next;
delete p;
return x;
}
template <class Element>
Element LinkStack<Element>::getTop()
{
return top->data;
}
template <class Element>
bool LinkStack<Element>::ifEmpty()
{
if (top)return 0;
else return 1;
}
template <class Element>
void LinkStack<Element>::menu()
{
int choice=0;
int pId = 0;
string pName;
int pAge = 0;
int pos = 0;
People p1 = { pId, pName, pAge };
Element x;
/*实现链栈的构造,析构,入栈,出栈,
取栈顶元素,判断栈空,菜单*/
cout <<"-----菜单-----"<< endl;
cout <<"1.取栈顶元素\t2.判断是否为空"<< endl;
cout <<"3.入栈\t4.出栈"<< endl;
cout <<"请输入你要实现的操作:";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
x = getTop();
cout<<"栈顶元素为:"<<x.id<<" "<<x.name<<" "<<x.age<<endl;
break;
case 2:
if (ifEmpty())
{
cout << "此栈为空" << endl;
}
else
{
cout << "此栈非空" << endl;
}
break;
case 3:
pId=0;
pAge=0;
pos=0;
cout << "请输入你要入栈的人物的id:";
cin >> pId;
cout << endl;
cout << "请输入你要入栈的人物的name:";
cin >> pName;
cout << endl;
cout << "请输入你要入栈的人物的age:";
cin >> pAge;
cout << endl;
p1={ pId, pName, pAge };
push(p1);
cout << endl;
break;
case 4:
x = pop();
cout << "出栈元素为:" << x.id << " " <<x.name << " " << x.age << endl;
break;
default:
cout << "你输入的数字有误,请重新输入" << endl;
break;
}
}
int main()
{
LinkStack<People> s1;
while (1)
{
s1.menu();
}
return 0;
}
数据结构8-链栈
最新推荐文章于 2024-07-24 17:54:05 发布