1. 程式人生 > >資料結構造輪子1-----棧

資料結構造輪子1-----棧

Stack.h

#pragma once

#define MAX_LENGTH 100

class Stack
{
public:
	virtual void InitStack() = 0;

	//主要操作
	virtual bool Push(int & data) = 0;
	virtual bool Pop(int & data) = 0;
	virtual bool isEmpty() = 0;
	//virtual bool isFull() = 0;

	//附加功能
	//virtual bool GetTop(int & data) = 0;
	virtual void ShowStack() = 0;
};

class Stack_Using_Array :public Stack
{
public:
	int top;
	int arr[MAX_LENGTH];

	void InitStack();

	bool Push(int & data);
	bool Pop(int & data);
	bool isEmpty();
	bool isFull();

	bool GetTop(int & data);
	void ShowStack();
};

class Stack_Using_Linklist :public Stack
{
public:
	struct node
	{
		int data;
		node * next;
	} * top;
	void InitStack();

	bool Push(int & data);
	bool Pop(int & data);
	bool isEmpty();
	//bool isFull();

	bool GetTop(int & data);
	void ShowStack();
};

Stack.cpp

#include "stdafx.h"
#include "iostream"
#include "Stack.h"

using namespace std;

//Stack_Usina_Arrty
void Stack_Using_Array::InitStack()
{
	top = -1;
}

bool Stack_Using_Array::Push(int & data)
{
	if (isFull())return false;
	arr[++top] = data;
	return true;
}

bool Stack_Using_Array::Pop(int & data)
{
	if (isEmpty())return false;
	data = arr[top--];
	return true;
}

bool Stack_Using_Array::isEmpty()
{
	if (top == -1)return true;
	else return false;
}

bool Stack_Using_Array::isFull()
{
	if (top == MAX_LENGTH - 1)return true;
	else return false;
}

bool Stack_Using_Array::GetTop(int & data)
{
	if (isEmpty())return false;
	data = arr[top];
	return true;
}

void Stack_Using_Array::ShowStack()
{
	if (isEmpty())cout << "Stack is empty";
	for (int i = top;i >= 0;i--)
	{
		cout << " " << arr[i] << " ";
	}
}

//Stack_Using_Linklist
void Stack_Using_Linklist::InitStack()
{
	top = NULL;
}

bool Stack_Using_Linklist::Push(int & data)
{
	node * temp = (node *)malloc(sizeof(node));
	temp->data = data;
	temp->next = top;
	top = temp;
	return true;
}

bool Stack_Using_Linklist::Pop(int & data)
{
	if (isEmpty())return false;
	data = top->data;
	top = top->next;
	return true;
}

bool Stack_Using_Linklist::isEmpty()
{
	if (top == NULL)return true;
	else return false;
}

bool Stack_Using_Linklist::GetTop(int & data)
{
	if (isEmpty())return false;
	data = top->data;
	return true;
}

void Stack_Using_Linklist::ShowStack()
{
	if (isEmpty())cout << "Stack is empty";
	node * temp = top;
	for (;temp != NULL;temp = temp->next)
	{
		cout << " " << temp->data << " ";
	}
}