链栈

来源:互联网 发布:手机真假检测软件 编辑:程序博客网 时间:2024/06/07 10:07
#include <stdio.h>#include <stdlib.h>struct lstack{char data;struct lstack * next;};struct lstack * init(){struct lstack * top;top = (struct lstack *)malloc(sizeof(struct lstack));top->data='0';top->next=NULL;return top;}int push(struct lstack * top,char data){struct lstack * p;p=(struct lstack *)malloc(sizeof(struct lstack));p->data=data;p->next=top->next;top->next=p;printf("%c入栈\n",data);return 0;}int pop(struct lstack * top){struct lstack * p;if(top->next==NULL){printf("栈空!删除失败!\n");}else{p = top->next;top->next=p->next;printf("%c出栈\n",p->data);free(p);}return 0;}int getTop(struct lstack * top){struct lstack * p;if(top->next==NULL){printf("栈空!无栈顶元素!\n");}else{p=top->next;printf("当前栈顶元素:%c\n",p->data);}return 0;}int getLength(struct lstack * top){struct lstack * p;p=top->next;int len=0;while(p!=NULL){len++;p=p->next;}printf("当前栈的长度为:%d\n",len);return 0;}void display(struct lstack * top){struct lstack * p;if(top->next==NULL){printf("栈空!无元素!\n");}else{p=top->next;printf("打印当前栈:");while(p!=NULL){printf("%c ",p->data);p=p->next;}printf("\n");}}int main(){struct lstack * s;s=init();push(s,'a');push(s,'b');push(s,'c');getLength(s);display(s);pop(s);pop(s);pop(s);pop(s);getLength(s);display(s);getTop(s); return 0;}

0 0