반응형
템플릿을 이용한 스택구현..
예제코드
#include <stdio.h>
enum BOOL {FALSE,TRUE};
template class CStack {
T* base;
T* sp;
int size;
public:
CStack(int s) { base=sp=new T[size=s]; }
~CStack() { delete[] base; }
void Push(T a) { *sp++=a; }
BOOL Pop(T& a) {
if (sp==base) return FALSE;
else { a=*--sp; return TRUE; }
}
int Size() const { return sp-base; }
};//template class CStack
class CXYStack {
CStack* xstack;
CStack* ystack;
public:
CXYStack(int size) {
xstack=new CStack(size);
ystack=new CStack(size);
}
~CXYStack() { delete xstack; delete ystack; }
void Push(int x,int y) { xstack->Push(x); ystack->Push(y); }
BOOL Pop(int& x,int& y) {
if (xstack->Size()==0)
return FALSE;
else {
xstack->Pop(x);
ystack->Pop(y);
return TRUE;
}
}
int Size() { return xstack->Size(); }
};//class CXYStack
void main()
{
CXYStack s(100);
int x,y;
s.Push(2,3);
s.Push(4,5);
s.Pop(x,y);
cout << x << endl << y << endl;
}
진수변환의 경우 stack자료구조가 가장 적합하다.
진수변환 예제소스코드..
```cpp
include
enum BOOL {FALSE,TRUE};
template class CStack {
T base;
T sp;
int size;
public:
CStack(int s) { base=sp=new T[size=s]; }
~CStack() { delete[] base; }
void Push(T a) { sp++=a; }
BOOL Pop(T& a) {
if (sp==base) return FALSE;
else { a=--sp; return TRUE; }
}
int Size() const { return sp-base; }
};//template class CStack
void main()
{
CStack s(100);
int n;
printf("Enter decimal digit:");
scanf("%d",&n);
while (n>=5) {
s.Push(n%5);
n/=5;
}//while
printf("Equivalent Quintett is ",n);
while (s.Pop(n))
printf("%d",n);
}//main ````
반응형