C++でチェーンスタックのインスタンスコードを実現
3285 ワード
チェーンスタックをカスタマイズし、c++言語で実現し、不足点を指摘してください.
// MyStack.cpp : 。
// , push( ),pop( ),top( ),size( ),empty( )
#include "stdafx.h"
#include
using namespace std;
//
template
struct NODE
{
NODE* next;
T data;
};
template
class MyStack
{
public:
MyStack()
{
phead = new NODE;
if (phead == NULL)
{
cout << "Failed to malloc a new node. " << endl;
}
else
{
phead->data = NULL;
phead->next = NULL;
}
}
//
void push(T e)
{
NODE* p = new NODE;
if (p == NULL)
{
cout << "Failed to malloc a new node. " << endl;
}
else
{
p->data = e;
p->next = phead->next;
phead->next = p;
}
}
//
T pop()
{
T e;
NODE* p = phead->next;
if(p != NULL)
{
phead->next = p->next;
e = p->data;
delete p;
return e;
}
else
{
cout << "There is no elements in the stack." << endl;
return NULL;
}
}
//
T top()
{
T e;
NODE* p = phead->next;
if (p != NULL)
{
e = p->data;
return e;
}
else
{
cout << "There is no elements in the stack." << endl;
return NULL;
}
}
//
int size()
{
int count(0);
NODE* p = phead->next;
while (p != NULL)
{
p = p->next;
count++;
}
return count;
}
// stack
bool empty()
{
NODE* p = phead;
if (p->next == NULL)
{
return true;
}
else
{
return false;
}
}
private:
NODE* phead;
};
int _tmain(int argc, _TCHAR* argv[])
{
MyStack sta;
sta.push(1);
sta.push(2);
sta.push(3);
cout << "The size of the stack now is " << sta.size() << endl;
sta.pop();
cout << "The top element is " << sta.top() << endl;
cout << "The size of the stack now is" << sta.size() << endl;
if (sta.empty())
{
cout << "This stack is empty." << endl;
}
else
{
cout << "This stack is not empty." << endl;
}
return 0;
}