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

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

代码如下:

linkstack.h  链表栈的头文件

#include 

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;
}


你可能感兴趣的:(数据结构与算法)