改善堆栈实施 [英] Improve stack implementation
本文介绍了改善堆栈实施的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是为堆栈实现编写了代码.欢迎提出任何改进代码的建议.
Hi,
I just wrote the code for a stack implementation. Any suggestion for the improvement of code is most welcome.
// StackTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
using namespace std;
class CStack
{
public:
int data;
CStack* ptr;
public:
void Push();
void Pop();
void Display();
};
CStack *ptrTop = NULL;
/* */
void CStack::Display()
{
CStack *ptrTopClone = ptrTop;
while(ptrTopClone != NULL)
{
cout<<ptrTopClone->data<<endl;
ptrTopClone = ptrTopClone->ptr;
}
}
/* */
void CStack::Push()
{
CStack *newData = new CStack;
cout<<"Please enter the data"<<endl<<endl;
cin>>newData->data;
newData->ptr =( ptrTop == NULL)? NULL: ptrTop;
ptrTop = newData;
}
/* */
void CStack::Pop()
{
if( ptrTop == NULL)
cout<<"Stack is empty"<<endl<<endl;
else
{
CStack *ptrPrevNode = ptrTop;
ptrTop = ptrPrevNode->ptr;
cout<<"*********"<<endl;
cout<<"Deleted Item is:"<<ptrPrevNode->data<<endl<<endl;
cout<<"*********"<<endl;
delete ptrPrevNode;
ptrPrevNode = NULL;//its better to set to NULL
}
}
/* */
int _tmain(int argc, _TCHAR* argv[])
{
int choice;
CStack *ptrStackImp = new CStack;
do
{
cout<<"*********"<<endl;
cout<<"1.PUSH"<<endl;
cout<<"2.POP"<<endl;
cout<<"3.DISPLAY"<<endl;
cout<<"0.EXIT"<<endl;
cin>>choice;
cout<<"*********"<<endl;
switch(choice)
{
case 1:
ptrStackImp->Push();
break;
case 2:
ptrStackImp->Pop();
break;
case 3:
ptrStackImp->Display();
break;
}
}while(choice!=0);
delete ptrStackImp;
ptrStackImp = NULL;
return 0;
}
推荐答案
我会将I/O
放到您的类之外,即Push
和Pop
方法的签名应为(IMHO):
I would putI/O
out of your class, i.e. the signature ofPush
andPop
methods should be (IMHO):
void Push( int i);// you may also choose a int return value (new stack size)
int Pop();
:)
首先使方法Push
,Pop
和Display
静态;然后将变量 ptrTop 设为该类的 private static 字段,并将字段ptr
设为 private字段:
First make the methodsPush
,Pop
andDisplay
static; then make the variable ptrTop a private static field of the class and the fieldptr
a private field:
class CStack
{
public:
int data;
private:
static CStack* ptrTop;
CStack* ptr;
public:
static void Push();
static void Pop();
static void Display();
};
CStack* CStack::ptrTop = NULL;
这样,您将拥有以下优势:
This way you''ll have the advantages below:
- 您无需实例化
CStack
对象即可调用Push
,Pop
和Display
方法
- you don''t need to instantiate a
CStack
object to call thePush
,Pop
andDisplay
methods
-
ptr
和ptrTop
变量受保护,不能在CStack
类代码之外访问和修改
- the
ptr
andptrTop
variables are protected from being accessed and modified outside theCStack
class code
这篇关于改善堆栈实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文