您的位置:首页 > 其它

链栈的基本操作

2016-04-24 22:07 435 查看
#include <stdio.h>
#include <stdlib.h>

typedef struct node{
char data;
node * next;
}LStack;

LStack * init(){
LStack * ls;
ls = (LStack *)malloc(sizeof(LStack));
ls->next = NULL;
return ls;
}

void push(LStack * ls,char x){
LStack * p;
p = (LStack *)malloc(sizeof(LStack));
p->data = x;
p->next = ls->next;
ls->next = p;
}

void pop(LStack * ls){
LStack * p;
char x;
if(ls->next == NULL){
printf("the stack is empty!\n");
}else{
p = ls->next;
ls->next = p->next;
x = p->data;
free(p);
}
}

void print(LStack * ls){
LStack * p;
p = ls->next;
while(p!=NULL){
printf("%4c",p->data);
p = p->next;
}
printf("\n");
}

int main(){
LStack * ls;
ls = init();
char x;
printf("please input the values of the stack!\n");
scanf("%c",&x);
while(x!='\n'){
push(ls,x);
scanf("%c",&x);
}
printf("\n");
print(ls);
printf("\n");
printf("after pop (once)\n");
pop(ls);
print(ls);
printf("after pop (twice)\n");
pop(ls);
print(ls);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: