程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 棧的順序存儲,所謂的順序棧

棧的順序存儲,所謂的順序棧

編輯:C++入門知識

與線性表類似棧也有兩種存儲結構,即順序存儲結構和鏈表存儲結構。棧的順序存儲結構亦稱為順序棧,它是運算受限的順序表。

#pragma once

class stack
{
public:
	stack(void);
	stack(int maxsize);
	~stack(void);
private:
	int *m_list;
	int m_maxsize;
	int m_top;
public:
	bool push(int value);
	bool pop();
	bool top(int *value);
	bool empty();
	bool full();
	int size();
	void output();
};

#include "StdAfx.h"
#include "stack.h"


stack::stack(void)
{
	m_maxsize = 10;
	m_list = new int[m_maxsize];
	for(int i=0; i<m_maxsize; i++)
	{
		m_list[i] = 0xFFFFFFFF;
	}
	m_top = -1;
}


stack::stack(int maxsize)
{
	m_maxsize = maxsize;
	m_list = new int[m_maxsize];
	for(int i=0; i<m_maxsize; i++)
	{
		m_list[i] = 0xFFFFFFFF;
	}
	m_top = -1;
}

stack::~stack(void)
{
	delete []m_list;
	m_top = -1;
	m_list = NULL;
}

bool stack::push(int value)
{
	if (!full())
	{
		m_list[m_top] = value;
		m_top++;
		return true;
	}
	return false;
}

bool stack::pop()
{
	if(!empty())
	{
		m_top--;
		return true;
	}
	return false;
}

bool stack::top(int *value)
{
	if (!empty())
	{
		*value = m_list[m_top - 1];
		return true;
	}
	*value = 0xFFFFFFFF;
	return false;
}

bool stack::empty()
{
	if (m_top == -1)
	{
		return true;
	}
	return false;
}

bool stack::full()
{
	if (m_top + 1 == m_maxsize)
	{
		return true;
	}
	return false;
}

int stack::size()
{
	return m_top + 1;
}

void stack::output()
{
	printf("---------------------------------\n");
	printf("stack information:\n");
	printf("maxsize=%d\n", m_maxsize);
	printf("top=%d\n", m_top);
	for(int i=0; i<m_top; i++)
	{
		printf("index%d=%d\n", i, m_list[i]);
	}
}
// sequstack.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stack.h"

int _tmain(int argc, _TCHAR* argv[])
{
	stack mystack(10);

	//入棧 0 --- 9
	/*for(int i=0; i<10; i++)
	{
		mystack.push(i);
	}
	
	if (mystack.full()) printf("stack is full\n");
	printf("stack size=%d\n", mystack.size());

	//出棧
	for(int i=0; i<10; i++)
	{
		int value = 0;
		mystack.top(&value);
		mystack.pop();
		printf("pop value=%d\n", value);
	}
	if (mystack.empty()) printf("stack is empty\n");
	printf("stack size=%d\n", mystack.size());*/

	mystack.push(8);
	mystack.push(9);
	mystack.push(10);
	mystack.push(11);
	
	printf("size=%d\n", mystack.size());
	int count = mystack.size();

	for(int i=0; i<count; i++)
	{
		int value = 0;
		mystack.top(&value);
		printf("value = %d\n", value);
		mystack.pop();
	}

	getchar();
	return 0;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved