关于栈的一些基本操作,用链表方式写的,持续更新中....
#include <iostream>
using namespace std;
typedef int DataType;
#define Node ElemType
class Node
{
public:
DataType date;
ElemType *next;
};
class StackLinkList
{
public:
StackLinkList(); //创建栈
~StackLinkList(); //摧毁栈
int IsEmpty(); //判断是否为空栈
int GetLength(); //获取栈的大小
void Push(DataType data); //入栈
void Pop(); //出栈
int GetTopElement(); //输出栈顶元素
void ClearAll(); //清空栈
void Traval();
private:
ElemType *top;
};
//创建栈
StackLinkList::StackLinkList()
{
top = NULL;
}
//摧毁栈
StackLinkList::~StackLinkList()
{
delete top;
}
//判断是否为空
int StackLinkList::IsEmpty()
{
return top == NULL;
}
//入栈 //头插法
void StackLinkList::Push(DataType data)
{
ElemType *newNode = new ElemType;
newNode->date = data;
newNode->next = NULL;
if (top == NULL)
{
top = newNode;
}
else
{
newNode->next = top;
top = newNode;
}
}
//出栈
void StackLinkList::Pop()
{
ElemType *p = top;
if (top == NULL)
{
cout << "栈空";
return;
}
top = top->next;
delete p;
}
//获取栈的大小
int StackLinkList::GetLength()
{
if (top == NULL)
{
return 0;
}
ElemType *p = top;
int count = 0;
while (p != NULL)
{
count++;
p = p->next;
}
return count;
}
//输出栈顶元素
int StackLinkList::GetTopElement()
{
if (top == NULL)
{
cout << "栈空";
return NULL;
}
return top->date;
}
//清空栈
void StackLinkList::ClearAll()
{
ElemType *p = top;
while (top != NULL)
{
top = top->next;
delete p;
p = top;
}
}
//遍历栈
void StackLinkList::Traval()
{
ElemType *p =top;
while (p)
{
cout <<p->date << " ";
p = p->next;
}
//注意不要用top,top是栈自己的属性,如果遍历后会把top指向最后一个,这样再入栈的话就会从0开始,所以要用一个索引p
}
int main()
{
StackLinkList s;
int i;
cout << "1.判断栈是否为空 2.获取栈的大小 3.入栈 4.出栈 5.获取栈顶值 6.清空栈 7.遍历栈 0.退出" << endl;
do
{
cout << "请输入要执行的操作:";
cin >> i;
switch (i)
{
case 1:
if (s.IsEmpty() == 1)
cout << "空栈" << endl;
else
{
cout << "不是空栈" << endl;
}
break;
case 2:
cout << "该栈的大小为" << s.GetLength() << endl;
break;
case 3:
int n;
cout << "请输入要入栈的值:";
cin >> n;
s.Push(n);
break;
case 4:
s.Pop();
break;
case 5:
cout << "栈顶的值为:" << s.GetTopElement() << endl;
break;
case 6:
s.ClearAll();
break;
case 7:
s.Traval();
break;
default:
cout << "输入的操作值错误" << endl;
break;
}
} while (i != 0);
system("pause");
return 0;
}