C++通用栈实现
#include
#include
#include
#include
typedef struct Node
{
void *pdata;
struct Node *pnext;
}Node,*PNode;
typedef struct CStack
{
int count;
int data_size;
Node *phead;
}CStack,*PCStack;
bool IsEmpty(PCStack ps)
{
return ps->phead == NULL;
}
void Destroy(PCStack ps)
{
Node *p;
while(ps->phead != NULL)
{
p = ps->phead;
ps->phead = p->pnext;
free(p->pdata);
free(p);
}
ps->count = 0;
}
void InitStack(PCStack ps,int data_size)
{
assert(ps != NULL);
if(ps==NULL && data_size<0)
{
return ;
}
ps->count = 0;
ps->data_size = data_size;
ps->phead = NULL;
}
static Node* BuyNode(PCStack ps,void *pdata)
{
Node *p = (Node*)malloc(sizeof(Node));
p->pdata =(char *) malloc(ps->data_size);
assert(p!=NULL && p->pdata!=NULL);
char *pd = (char *)pdata;
memcpy(p->pdata,pd,ps->data_size);
return p;
}
bool Push(PCStack ps,void *pdata)
{
Node *p = BuyNode(ps,pdata);
p->pnext = ps->phead;
ps->phead = p;
ps->count++;
return true;
}
bool GetTop(PCStack ps,void *rtval)
{
if(IsEmpty(ps))
{
return false;
}
char *rt = (char *)rtval;
char *tmp = (char*)ps->phead->pdata;
memcpy(rt,tmp,ps->data_size);
return true;
}
bool Pop(PCStack ps,void *rtval)
{
if(IsEmpty(ps))
{
return false;
}
Node *p = ps->phead;
char *rt = (char *)rtval;
char *tmp = (char*)p->pdata;
memcpy(rt,tmp,ps->data_size);
ps->phead = p->pnext;
free(p->pdata);
free(p);
ps->count--;
return true;
}
int main()
{
CStack ss;
InitStack(&ss,sizeof(char*));
char *p[8] = {"123","1234","12345","abc","abcd","xyz","123abcd","123abcdxyz"};
int i;
char* ptmp;
for(i=0 ; i<8 ; i++)
{
Push(&ss,(void*)&p[i]);
}
while(!IsEmpty(&ss))
{
GetTop(&ss,(void*)&ptmp);
printf("%s\n",ptmp);
Pop(&ss,(void*)&ptmp);
}
Destroy(&ss);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143