欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++实现栈的操作(push和pop)

程序员文章站 2024-02-14 17:32:16
...

栈的组织形式:

C++实现栈的操作(push和pop)

如上图所示:栈也是有多个数据节点组成的,每个节点包含有数据域和指向下一个节点的指针域。并且每次的push、pop和判空都是操作的栈顶指针top。

栈中每个数据节点的定义:

class data_node{
public:
	data_node() :data(0), next(NULL){}//default constructer function
	data_node(int value) :data(value), next(NULL){}//include arg constructer function
	int data;
	data_node *next;//pointer that point to next node
};

栈的类的定义:

class my_stack{
public:
	my_stack() :top(NULL){}
	void push(data_node new_data);
	void pop(data_node *pop_node);
	bool empty();
	data_node *top;
};

栈的push操作:

void my_stack::push(data_node new_data)
{
	data_node *pnode = NULL;
	pnode = new data_node(new_data.data);
	pnode->next = top;
	top = pnode;
}

void my_stack::pop(data_node *pop_node)
{
	if (empty())
	{
		printf("this stack is empty\n");
		return;
	}
	pop_node->data = top->data;
	data_node *pnode = top;
	top = top->next;
	delete pnode;
}

bool my_stack::empty()
{
	return (top == NULL);
}

 


完整的代码如下:

#include "stdafx.h"
#include <iostream>
#pragma warning(disable:4996)
#include <string>

using namespace std;

class data_node{
public:
	data_node() :data(0), next(NULL){}//default constructer function
	data_node(int value) :data(value), next(NULL){}//include arg constructer function
	int data;
	data_node *next;//pointer that point to next node
};

class my_stack{
public:
	my_stack() :top(NULL){}
	void push(data_node new_data);
	void pop(data_node *pop_node);
	bool empty();
	data_node *top;
};

void my_stack::push(data_node new_data)
{
	data_node *pnode = NULL;
	pnode = new data_node(new_data.data);
	pnode->next = top;
	top = pnode;
}

void my_stack::pop(data_node *pop_node)
{
	if (empty())
	{
		printf("this stack is empty\n");
		return;
	}
	pop_node->data = top->data;
	data_node *pnode = top;
	top = top->next;
	delete pnode;
}

bool my_stack::empty()
{
	return (top == NULL);
}

int main()
{
	data_node pop_node(0);
	my_stack stack;
	stack.push(3);
	stack.push(2);
	stack.push(6);//3,2,6
	stack.pop(&pop_node);
	//printf("is empty? %d\n", stack.empty());
	printf("%2d ", pop_node.data);
	stack.pop(&pop_node);
	//printf("is empty? %d\n", stack.empty());
	printf("%2d ", pop_node.data);
	stack.pop(&pop_node);
	printf("%2d\n ", pop_node.data);
	printf("is empty? %d\n", stack.empty());
	return 0;
}