数据结构——栈的工作原理

栈的工作原理

  • 主函数

栈的核心原理:先进后出规则

Mystack *pStack = new Mystack(5);//初始化操作
对象创建在堆上直接赋值给指针,结束时需要用delete释放内存,并将pStack指向空

Mystack mystack(4);在栈上创建对象,函数结束时无需释放内存,系统自动退栈

#include <iostream>
#include "Mystack.h"

using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
	Mystack *pStack = new Mystack(5);//初始化操作 
	

	pStack->push( 'a' ); //底 
	pStack->push( 'b' ); 
	pStack->push( 'c' ); 
	pStack->push( 'd' ); 
	pStack->push( 'e' ); //顶 

	cout << "The length of Stack is "<<pStack->stackLength() << endl << endl; 
 
	pStack->stackTraverse();

	char elem;
	pStack->pop(elem);
	cout << "The out element is " << elem << endl << endl;
	pStack->stackTraverse();
	cout << "The length of Stack is "<<pStack->stackLength() << endl << endl; 
 
		
	if(pStack->stackEmpty())//判断是否为空 
		cout << "Empty" << endl;
	Mystack mystack(4);
	mystack.push('j');
	mystack.stackTraverse();
		cout << endl << endl;
	cout << "The length of the Stack is " << mystack.stackLength();
	
	delete pStack;
	pStack = NULL;
	return 0;
}
  • Mystack头文件

    #ifndef MYSTACK_H
    #define MYSTACK_H

     class Mystack
     {
     public:
     	Mystack(int size);
     	~Mystack();
     	bool stackEmpty();
     	bool stackFull();
     	void clearStack();
     	int stackLength();
     	bool push(char elem);		
     	bool pop(char  &elem);
     	void stackTraverse();
     protected:
     	char *m_p;
     	int m_iSize;
     	int m_iTop;
     
     };
     
     #endif
    
  • Mystack cpp文件

    #include <iostream>
     #include "Mystack.h"
     
     using namespace std;
     
     Mystack:: Mystack(int size){
     	m_iSize = size;
     	m_p = new char[size];
     	m_iTop = 0;
     }
     
     Mystack::~Mystack(){
     	delete []m_p;
     }
     
     bool Mystack::stackEmpty(){
     	if( 0 == m_iTop ){ 	
     		return true;
     	}
     	else 
     		return false;
     }
     
     bool Mystack::stackFull(){
     	if( m_iSize == m_iTop )
     		return true;
     	else
     		return false;
     }
     
     void Mystack::clearStack(){
     	m_iTop = 0;
     }
     
     int Mystack::stackLength(){
     	return m_iTop;
     }
     
     bool Mystack::push(char elem){
     	if( stackFull() ){
     		return false;
     	}
     	
     	m_p[m_iTop] = elem;
     	m_iTop++;
     	return true;
     }
     
     bool Mystack::pop( char &elem){
     	if( stackEmpty() )
     		return false;
     	else 
     		elem = m_p[--m_iTop];
     	return true;
     }
     
     void Mystack::stackTraverse(){
     	int temp = 0;
     	while( temp < m_iTop ){
     	cout << m_p[temp] << " ";
     		temp ++;
     	} 
     }
    

演示结果:
数据结构——栈的工作原理

  • 学习慕课栈模版和栈事例

注:本文知识从慕课james_yuan学习