以下是我有学数据结构的时侯编写的:
存储方式为链式存储结构:
typedef struct snode
{
DataType data;
struct snode *next;
}LSNode;
void StackInitiate(LSNode **head)
{
if((*head=(LSNode *)malloc(sizeof(LSNode)))==NULL) exit(1);
(*head)->next=NULL;
}
int StackNotEmpty(LSNode *head)
{
if(head->next==NULL) return 0;
else return 1;
}
int StackPush(LSNode *head,DataType x)
{
LSNode *p;
if((p=(LSNode*)malloc(sizeof(LSNode)))==NULL)
{
printf("There is not enough space for being inserted in Function StackPush\n");
printf("Press any key to end .\n");
getch();
return 0;
}
p->data=x;
p->next=head->next;
head->next=p;
return 1;
}
int StackPop(LSNode *head,DataType *d)
{
LSNode *p=head->next;
if(p==NULL)
{
printf("Stack is empty in Function StackPop !\n");
printf("Press any key to end.\n");
getch();
return 0;
}
head->next=p->next;
*d=p->data;
free(p);
return 1;
}
int StackTop(LSNode *head,DataType *d)
{
LSNode *p=head->next;
if(p==NULL)
{
printf("Stack is empty in StackTop.\n");
printf("Press any key to end .\n");
getch();
return 0;
}
*d=p->data;
return 1;
}
void StackDestroy(LSNode *head)
{
LSNode *p,*p1;
p=head;
while(p!=NULL)
{
p1=p;
p=p->next;
free(p1);
}
return ;
}
存储方式为顺序存储结构:
typedef struct
{
DataType stack[MaxStackSize];
int top;
}SeqStack;
void StackInitiate(SeqStack *S)
{
S->top=0;
}
int StackNotEmpty(SeqStack S)
{
if(S.top<=0) return 0;
else return 1;
}
int StackPush(SeqStack *S,DataType x)
{
if(S->top>=MaxStackSize)
{
printf("Stack is full now,not being inserted!\n");
return 0;
}
else
{
S->stack[S->top]=x;
S->top++;
return 1;
}
}
int StackPop(SeqStack *S,DataType *d)
{
if(S->top<=0)
{
printf("Stack is empty now, not having any data.\n");
return 0;
}
else
{
S->top--;
*d=S->stack[S->top];
return 1;
}
}
int StackTop(SeqStack S,DataType *d)
{
if(S.top<=0)
{
printf("Stack is empty now!\n");
return 0;
}
else
{
*d=S.stack[S.top-1];
return 1;
}
}