和队列一样简单实现push() pop() print()基本功能。
#include<stdio.h>
#include<stdlib.h>
typedef int elemType;
typedef struct sNode{
elemType info;
struct sNode *next;
}sNode;
typedef struct {
int node;
sNode * top;
}LinkStack;
void initStack(LinkStack *s){
s->node = 0;
s->top = NULL;
}
void push(LinkStack *s, elemType value){
sNode *ptr = (sNode *)malloc (sizeof(sNode));
ptr->info = value;
if(0 == s->node){
ptr->next = NULL;
}
else{
ptr->next = s->top;
}
s->top = ptr;
s->node++;
}
void * getTop(LinkStack *s){
if(0 == s->node){
printf("Empty stack.\n");
return NULL;
}
elemType *elem = &s->top->info;
return elem;
}
void pop(LinkStack *s){
sNode *ptr = s->top;
if( 0 == s->node){
printf("Empty Stack.\n");
}
else{
s->top = s->top->next;
s->node--;
free(ptr);
}
return;
}
void printStack(LinkStack *s){
if(0 == s->node){
return;
}
int i = 0;
sNode *ptr = s->top;
while(i < s->node-1){
printf("%d -> ",ptr->info);
ptr = ptr->next;
i++;
}
printf("%d\n",ptr->info);
return;
}
int main(){
elemType i;
elemType *p;
LinkStack stack;
initStack(&stack);
pop(&stack);
if((p=getTop(&stack)) != NULL)
printf("%d\n",*p);
for(i=0;i<10;i++){
push(&stack,i);
printStack(&stack);
}
if((p=getTop(&stack)) != NULL)
printf("%d\n",*p);
for(i=0;i<12;i++){
pop(&stack);
printStack(&stack);
}
return 0;
}
微信扫一扫,订阅我的博客动态^_^