/************************************************************************/
/* 使用c++实现Stack */
/************************************************************************/
#include <stdio.h>
class Stack
{
public:
Stack();
~Stack();
void Push(void* data);
void* Pop();
protected:
typedef struct elementT {
struct elementT* next;
void* data;
}element;
element* firstElement;
};
Stack::Stack() {
firstElement = NULL;
return;
}
Stack::~Stack() {
element* next;
while (firstElement)
{
next = firstElement->next;
delete firstElement;
firstElement = next;
}
return;
}
void Stack::Push(void* data) {
element* ele = new element;
ele->data = data;
ele->next = firstElement;
firstElement = ele;
return;
}
void* Stack::Pop() {
element* popElement = firstElement;
void* data;
if (firstElement == NULL)
{
//handle the error
//throw StackError(E_EMPTY);
}
data = firstElement->data;
firstElement = firstElement->next;
delete popElement;
return data;
}
/************************************************************************/
/* 使用c语言实现Stack */
/************************************************************************/
#include <memory>
typedef struct elementT {
struct elementT* next;
void* data;
}element;
int CreateStack(element **stack)
{
*stack = NULL;
return 1;
}
int Push(element** stack, void* data)
{
element* ele;
ele = (element*) malloc(sizeof(element));
if (!ele)
{
return 0;
}
ele->data = data;
ele->next = *stack;
*stack = ele;
return 1;
}
int Pop(element** stack, void** data)
{
element* ele;
if (!(ele = *stack))
{
return 0;
}
*data = ele->data;
*stack = ele->next;
free(ele);
return 1;
}
int DeleteStack(element** stack)
{
element* next;
while (*stack)
{
next = (*stack)->next;
free(*stack);
*stack = next;
}
return 1;
}
</memory></stdio.h>