【栈】用链表实现栈

#include 
using namespace std;

class stack
{
public:
	char element;
	stack* next;
};

class op_stack
{
public:
	stack* my_stack;

	op_stack()
	{
		my_stack = new stack;
		my_stack->next = NULL;
	}

	int push(stack* my_stack, char temp)
	{
		int count = 0;
		stack* ptr1 = my_stack, *ptr2=NULL ;
		while (ptr1)
		{
			ptr2 = ptr1;
			ptr1 = ptr1->next;
			count++;
		}
		if (count == 501 )
		{
			cout << "已经到达了上限" << endl;
			return 0;
		}
		ptr1 = new (stack);
		ptr1->element = temp;
		ptr1->next = NULL;
		ptr2->next = ptr1;
		cout << "push元素成功" << endl;
		return 1;
	}

	int pop(stack* my_stack, char* temp)
	{
		stack* ptr1 = my_stack, * ptr2=NULL;
		while (ptr1->next!=NULL)
		{
			ptr2 = ptr1;
			ptr1 = ptr1->next;
		}
		if (ptr1 == my_stack)
		{
			cout << "此时栈没有元素,不能pop" << endl;
			return 0;
		}

		*temp = ptr1->element;
		delete ptr1;
		ptr2->next = NULL;
		cout << "pop出了 " << *temp << endl;
		return 1;
	}

	int print_stack(stack* my_stack)
	{
		stack* ptr = my_stack->next;
		if (ptr == NULL)
		{
			cout << "栈没有元素" << endl;
			return 0;
		}
		while (ptr)
		{
			cout << ptr->element << " ";
			ptr = ptr->next;
		}
		cout << endl;
		return 1;
	}

	void op_clear()
	{
		system("cls");
	}

	int Is_empty(stack* my_stack)
	{
		stack* ptr = my_stack;
		while (ptr->next)
		{
			ptr = ptr->next;
		}
		if (ptr == my_stack)
		{
			cout << "栈是空的" << endl;
			return 0;
		}
		else
		{
			cout << "栈有元素" << endl;
			return 1;
		}
	}
};

int main()
{
	op_stack my_op_stack;
	
	int choose;
	while (1)
	{
		cout << "push一个元素请按 1" << endl;
		cout << "pop一个元素请按 2" << endl;
		cout << "判断是否为空请按 3" << endl;
		cout << "输出栈空间元素请按 4(从栈顶到栈底)" << endl;
		cout << "清空页面请按 5 " << endl;
		cout << "退出请按 6 " << endl;
		cout << "请输入你的选择" << endl;
		cin >> choose;
		switch (choose)
		{
		case 1:
		{
			char temp;
			cout << "请输入一个元素" << endl;
			cin >> temp;
			my_op_stack.push(my_op_stack.my_stack, temp);
			break;
		}

		case 2:
		{
			char temp;
			my_op_stack.pop(my_op_stack.my_stack, &temp);
			break;
		}

		case 3:
		{
			my_op_stack.Is_empty(my_op_stack.my_stack);
			break;
		}

		case 4:
		{
			my_op_stack.print_stack(my_op_stack.my_stack);
			break;
		}

		case 5:
		{
			my_op_stack.op_clear();
			break;
		}

		case 6:
		{
			return 0;
		}

		default:
			cout << "输入有误" << endl;
			break;
		}
	}
	return 0;
}

你可能感兴趣的:(链表,c++,算法)