Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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;
}
Posted
Updated 6-May-10 21:15pm
v2

I would put I/O out of your class, i.e. the signature of Push and Pop methods should be (IMHO):
void Push( int i);// you may also choose a int return value (new stack size)
int Pop();

:)
 
Share this answer
 
First make the methods Push, Pop and Display static; then make the variable ptrTop a private static field of the class and the field ptr a private field:

C++
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:


    • you don't need to instantiate a CStack object to call the Push, Pop and Display methods

    • the ptr and ptrTop variables are protected from being accessed and modified outside the CStack class code

 
Share this answer
 
Comments
CPallini 7-May-10 3:09am    
The 'static methods' improvement is arguable: suppose, for instance, you need two stacks...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900