Implementation of C++ Stack

Because I will graduate to work in one year, I feel that the hand of coding is a bit raw, especially for data structures and algorithms, so I have never blogged and started blogging. The blog is updated as it happens, and it is only for recording purposes. You are welcome to point out mistakes and places that do not conform to general programming habits.

When I was learning data structures, I always had a question. Why should queues and stacks have a fixed maximum length? It’s okay to not fix them, as long as they have the correct operational attributes?

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

class Stack
{
public:
	Stack();
	void Push(int data);//Push the stack
	void Pop();//Pop stack
	void Print();//Print stack
private:
	Node *top;//Top of stack
	Node *buttom;//The bottom of the stack
	int size;//Number of stack elements
};
//stack.cpp
#include<iostream>
#include"stack.h"
using namespace std;

Stack::Stack()
{
	top = NULL;
	buttom = NULL;
	size = 0;
	cout << "Stack: This is an empty 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: Push successfully!" << endl;
}

void Stack::Pop()
{
	if (size == 0)
	{
		cout << "Pop: Empty stack cannot be popped!" << endl;
		return;
	}
	if (size == 1)
	{
		Node *temp;
		temp = top;
		top = NULL;
		buttom = NULL;
		size--;
		delete temp;
		cout << "Pop: popped successfully, the stack is empty!" << endl;
		return;
	}
	Node * temp1, * temp2;
	temp1 = top;
	temp2 = buttom;
	while (temp2->next!=top)
	{
		temp2 = temp2->next;
	}
	top = temp2;
	size--;
	delete temp1;
	cout << "Pop: popped successfully!" << endl;
}

void Stack::Print()
{
	if (size==0)
	{
		cout << "Print: stack is empty!" << endl;
		return;
	}
	Node *temp;
	temp = buttom;
	cout << "Print: There are "<< size <<" elements in the stack, which are: ";
	while (temp!=top)
	{
		cout << temp->data << ",";
		temp = temp->next;
	}
	cout << top->data << endl;
}

intmain()
{
	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;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326482799&siteId=291194637