用C++中的类来实现链式栈

数据结构在C程序设计中显得尤为重要,但在C++用好像就好像用到,而且可以用模板编程,好像我们不需要设计数据结构,但要我们自己来设计一栈类又该怎么设计呢?

栈类的头文件

#ifndef STACK_H_
#define STACK_H_
#include<iostream.h>
struct Node
{
	int data;
	struct Node* next;
};
class Stack
{
public:
	Stack();
	void push(int x);
	void pop(int *e);
	void show();
	int get_count()
	{
		return count;
	}
private:
	Node* top;
	Node* bottom;
	int count;
};
#endif


栈类的实现

#include"Stack.h"
Stack::Stack()
{
	top=NULL;
	bottom=top;
	count =0;
}
void Stack::push(int x)
{
	Node *temp;
	temp=new Node;
	temp->next=top;
	temp->data=x;
	top=temp;
	count++;
}
void Stack::pop(int *e)
{
	Node *temp;
	temp=top;
	*e = top->data;
	top=top->next;
	delete temp;
	count--;
}
void Stack::show()
{
	Node* temp=top;
	if(temp==NULL)
	{
		cout<<"zhan is empty!";
	}
	else
	{
		while(temp!=NULL)
		{
			cout<<temp->data<<"  ";
			temp=temp->next;
		}
	}
	cout<<endl;
}

main函数

#include <iostream>
#include "Stack.h"
#include <time.h>
int main(void)
{
	Stack a;
	int x,n,i;
	srand(time(0));
	int e;
	for(i=0;i<10;i++)
	{
		a.push(rand()%10+1);
	}
	a.show();
	{
		a.pop(&e);
	}
	a.show();
	cout << e <<endl;
	cout <<a.get_count() <<endl;
	return 0;
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值