用c++实现了数组栈和链式栈,栈是一种特殊的线性表,只能一头进出,在函数递归时应用挺大的。
</pre><pre name="code" class="cpp">
//这是数组栈
#include
#include
using namespace std;
#define size 20
class stack
{
public:
stack()
{
number = 0;
}
void push(int c)
{
if (number == size)
{
cout << "栈已经满了,无法在插入了" << endl;
return;
}
else
{
number++;
a[number] = c;
}
}
void pop()
{
if (number == 0)
{
cout << "栈已经空" << endl;
return;
}
else
{
cout << "出栈元素是" << a[number] << endl;
number--;
}
}
void show()
{
cout << "栈里现在有元素的个数是" << number << endl;
}
private:
int a[size];
int number;
};
int main()
{
class stack stack1;
int c;
string str1;
cout << "输入y进行入栈 输入n进行出栈, 输入k显示当前栈中元素的个数, 输入x退出" << endl;
cin >> str1;
while (str1[0] != 'x')
{
if (str1[0] == 'y')
{
cout << "输入你要入栈的元素" << endl;
cin >> c;
stack1.push(c);
}
else if (str1[0] == 'n')
{
stack1.pop();
}
else if (str1[0] == 'k')
stack1.show();
cout << "输入y进行入栈输入n进行出栈,输入k显示当前栈中元素的个数,输入x退出" << endl;
cin >> str1;
}
return 0;
}
//这是链式栈
//链表实现栈,栈就是线性表的特例,所以链式栈就是和链表一样的定义,实现上稍微不同。
#include
#include
#include
using namespace std; typedef int elem; class stacknode //栈节点类, { public: stacknode *next;//需要被其他类的函数访问和使用, elem ele; stacknode( elem v, stacknode *nextp = NULL)//构造函数,只是构造数值 { ele = v; next = nextp; } stacknode(stacknode *nextp = NULL)//构造指针 { next = nextp;//第一个插入的元素的指针域就是NULL. } ~stacknode(){} }; class Linkstack { private: stacknode *top;//栈顶指针,只是被本类的函数访问 public: int number=0; Linkstack( int count = 20)//链栈初始化,构造函数 { top = NULL;//数组栈中top赋数值,链式栈应该是null。 } void clear(); ~Linkstack(){ clear();}//析构函数 void show() { cout << "栈里现在有元素的个数是" << number << endl; } void push( elem v) { top = new stacknode(v, top);//初始化。top指向新节点,v作为第一个节点的数值,null作为指针域。 number++; } elem pop(); elem topValue() { assert(!isEmpty()); return top->ele; } bool isEmpty() { return top = NULL; } }; void Linkstack::clear() { while (top != NULL) { stacknode *p = top; top = top->next; delete p; } } elem Linkstack::pop() { elem temp; assert(!isEmpty()); stacknode *p = top; temp = top->ele; top = top->next; delete p; number--; return temp; } int main() { Linkstack stack1; elem c=0; char str1; cout << "输入a进行入栈 输入b进行出栈, 输入c显示当前栈中元素的个数, 输入d退出" << endl; cin >>str1; while (str1!= 'd') { if (str1 == 'a') { cout << "输入你要入栈的元素" << endl; cin >> c; stack1.push(c); } else if (str1 == 'b') { stack1.pop(); } else if (str1 == 'c') stack1.show(); cout << "输入a进行入栈 输入b进行出栈,输入c显示当前栈中元素的个数,输入d退出" << endl; cin >> str1; } return 0; }