链表栈的基本操作的实现---入栈、出栈、清空

利用链表的结构实现栈的功能---入栈、出栈、清空

代码如下:

linkstack.h  链表栈的头文件

#include <iostream>

class Node 
{
public:
	int data;
	Node * next;

};

class stack
{
private:
	Node *head;
	Node *pcurr;
	int length;

public:
	stack()
	{
		head = NULL;
		int len = 0; // 有头结点后lens初始值为0
	}

	void push(int val);//入栈
	int pop();//出栈
	int len();//判断长度
	bool isEmpty();//
	void clear();//清空栈中所有元素
};

linkstack.cpp 链表栈的子函数功能实现

#include "linkstack.h"

using namespace std;

void stack::push(int val)
{
	Node *ptemp ;
	ptemp = new Node();
	ptemp->data = val;
	length++;
	if(head == NULL)
	{
	   ptemp->next = head;
	   head = ptemp;
	   pcurr = ptemp;
	}
	else 
	{
		ptemp->next = pcurr;
		pcurr = ptemp;
	}

}

bool stack::isEmpty()
{
	if(length == 0)
		return 1;
	else 
		return false;

}


int stack::pop()
{
	if(isEmpty() == 1)
	{
		cout << "is empty" << endl;
		return 0;
	}
	else
	{
	    Node *ptemp ;
		ptemp = new Node();
		length--;
		ptemp = pcurr;
		int data = pcurr->data; //返回删除元素的值;
		delete(ptemp);// 删除该元素
		pcurr = pcurr->next;
		cout <<"需要删除的元素"<< data << endl;
		return data;

	}
	
}


void stack::clear()
{
	if(length > 0)
		pop();
}

测试主函数:

#include "linkstack.h"
using namespace std;

int main()
{
	stack stack;
	if (stack.isEmpty() == 0)
		cout << "is empty" << endl;
	stack.push(1);
	stack.push(2);
	stack.push(3);

	stack.pop();

	stack.clear();
	stack.isEmpty();
	if (stack.isEmpty() == 0)
		cout << "is empty" << endl;

	system("pause");
	return 0;
}


  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值