链表栈的实现

   在Linux的环境下编辑代码 . 

#include<iostream>
#include<stdlib.h>
using namespace std;

//定义节点
struct Node
{
	//数据域:
	int data;
	//指向域
	struct Node* next;//指向域
};
//栈类
class Cstack
{
//方法
public:
	Cstack();//构造函数
	//栈为满 
	bool IsFull();
	bool IsEmpty();
	bool push(int);
	bool pop(int&);
	unsigned short stackLength();//栈的元素的长度
//容量:指向链表的头节点
private:
	Node *top;//top指向栈的链表
	unsigned short ilen;//元素的个数
};
Cstack::Cstack()
{
	top=NULL;//指向空链表
	ilen=0;//长度为0
}
bool Cstack::IsFull()
{
	return false;    //链表会申请空间,故不用考虑为满.
}
bool Cstack::IsEmpty()
{
	if(NULL==top)      
		return true;					
	else	
		return false;
}
bool Cstack::push(int d)
{
    //1分配节点:(头插法)
	Node* pnew=(Node*)malloc(sizeof(Node));//分配空间:长度
	if(NULL==pnew)
		return false;
	pnew->data=d;

	//个数
	ilen++;
    //2修改指向域
	pnew->next=top;//新节点指向链表头
	top=pnew;
	return true;
}
bool Cstack::pop(int& value)
{
    //栈是否为空
	if(IsEmpty())
		return false;
	Node* ptemp=top;
	value=top->data;//先返回值:
	//释放
	top=top->next;
	free(ptemp);

	//长度-1
	ilen--;
	return true;
}
unsigned short Cstack::stackLength()
{
	return ilen;
}
int main()
{
//实例化:请会计
//进栈
	Cstack s;
	s.push(1);
	s.push(2);
	s.push(3);
	
	//栈的长度
	cout<<s.stackLength()<<endl;
	//出栈
	int value;
	while(s.pop(value))
		cout<<value<<" ";

	cout<<endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/Superman___007/article/details/81583894
今日推荐