C++栈的实现

因为还有一年就毕业参加工作了,感觉码代码的手有点生,特别是对于数据结构和算法,所以从不写博客的我开始写博客了。博客随缘更新,只做记录用,欢迎大佬指出错误以及不符合一般编程习惯的地方。

当年学数据结构的时候一直有个疑问,为啥队列和栈都要固定最大长度,不固定也可以的吧,只要具有正确的操作属性?

//stack.h
class Node
{
public:
	int data;
	Node *next;
};

class Stack
{
public:
	Stack();
	void Push(int data);//入栈
	void Pop();//出栈
	void Print();//打印栈
private:
	Node *top;//栈顶
	Node *buttom;//栈底
	int size;//栈元素数量
};
//stack.cpp
#include<iostream>
#include"stack.h"
using namespace std;

Stack::Stack()
{
	top = NULL;
	buttom = NULL;
	size = 0;
	cout << "Stack: 这是一个空栈" << endl;
}


void Stack::Push(int data)
{
	Node *temp;
	temp = (Node *)new Node[1];
	temp->data = data;
	temp->next = NULL;
	if (size==0)
	{
		top = (Node *)new Node[1];
		buttom = temp;
	}
	top->next = temp;
	top = temp;
	size++;
	cout << "Push: 入栈成功!" << endl;
}

void Stack::Pop()
{
	if (size == 0)
	{
		cout << "Pop: 空栈无法出栈!" << endl;
		return;
	}
	if (size == 1)
	{
		Node *temp;
		temp = top;
		top = NULL;
		buttom = NULL; 
		size--;
		delete temp;
		cout << "Pop: 出栈成功,栈已为空!" << endl;
		return;
	}
	Node *temp1, *temp2;
	temp1 = top;
	temp2 = buttom;
	while (temp2->next!=top)
	{
		temp2 = temp2->next;
	}
	top = temp2;
	size--;
	delete temp1;
	cout << "Pop: 出栈成功!" << endl;
}

void Stack::Print()
{
	if (size==0)
	{
		cout << "Print: 栈为空!" << endl;
		return;
	}
	Node *temp;
	temp = buttom;
	cout << "Print: 栈内元素共"<< size <<"个,分别为: ";
	while (temp!=top)
	{
		cout << temp->data << ",";
		temp = temp->next;
	}
	cout << top->data << endl;
}

int main()
{
	Stack stack;
	stack.Print();
	stack.Push(1);
	stack.Push(2);
	stack.Push(3);
	stack.Push(4);
	stack.Print();

	cout << "******************" << endl;
	stack.Pop();
	stack.Print();
	cout << "******************" << endl;
	stack.Pop();
	stack.Print();
	cout << "******************" << endl;
	stack.Pop();
	stack.Print();
	cout << "******************" << endl;
	stack.Pop();
	stack.Print();
	cout << "******************" << endl;
	stack.Pop();
	stack.Print();
	cout << "******************" << endl;
	return 0;
}


猜你喜欢

转载自blog.csdn.net/h294455907/article/details/80233575