1.数组方式
#include<stdio.h>
#include<stdlib.h>
#define N 100
struct stack {
int top;
int data[N];
};
struct stack mystack = { -1,{0} };
int isempty()
{
if (mystack.top == -1)
{
return 1;
}
else
{
return 0;
}
}
void setempty()
{
mystack.top = -1;
}
int push(int data)
{
if (mystack.top + 1 <= N - 1)
{
mystack.data[mystack.top+1] = data;
mystack.top += 1;
return 1;
}
else
{
return 0;
}
}
int pop()
{
if (isempty() == 0)
{
mystack.top -= 1;
return mystack.data[mystack.top + 1];
}
else
{
return -1;
}
}
2.链表方式
#include<stdio.h>
#include <stdlib.h>
#define datatype int
struct stacknode {
int num;
datatype data;
struct stacknode* next;
};
typedef struct stacknode StackNode;
StackNode* init(StackNode* phead)
{
return NULL;
}
StackNode* push(StackNode* phead, int num, datatype data)
{
StackNode* pnewnode = malloc(sizeof(StackNode));
pnewnode->num = num;
pnewnode->data = data;
pnewnode->next = NULL;
if (phead == NULL)
{
phead->next = pnewnode;
}
else
{
StackNode* p = phead;
while (p->next != NULL)
{
p = p->next;
}
p->next=pnewnode;
}
return phead;
}
StackNode* pop(StackNode* phead, StackNode* outdata)
{
if (phead==NULL)
{
return NULL;
}
else if (phead->next==NULL)
{
outdata->data = phead->data;
outdata->num = phead->num;
free(phead);
phead = NULL;
return phead;
}
else
{
StackNode* p = phead;
while (p->next->next != NULL)
{
p = p->next;
}
outdata->data = phead->next->data;
outdata->num = phead->next->num;
free(p->next);
p->next = NULL;
return phead;
}
}
StackNode* freeall(StackNode* phead)
{
if (phead==NULL)
{
return;
}
else
{
StackNode* p1, * p2;
p1 = phead;
while (p1->next != NULL)
{
p2 = p1->next;
p1->next = p2->next;
free(p2);
}
free(phead);
return NULL;
}
}
void test()
{
StackNode* phead=NULL;
phead=init(phead);
phead = push(phead, 1, 1);
phead = push(phead, 2, 10);
phead = push(phead, 3, 11);
StackNode* out = malloc(sizeof(StackNode));
while (phead->next != NULL)
{
pop(phead, out);
}
}