数据结构之链栈的基本操作(出栈,入栈,显示,求栈的长度)

//将12345依次入栈,取栈顶元素,将6,7入栈,求栈中元素个数,将7出栈,将6出栈,将5出栈,最后全部出栈依次输出 #include#include#include#include#define maxsize 100using namespace std;typedef struct node{ int data; struct node *next;}lnode ,*linkstack; void init(linkstack *top){ if( ( (*top)=(linkstack)malloc(sizeof(lnode)) )==NULL )//(给*top分配一个存储空间让top指向这个空间) exit(-1); (*top)->next=NULL;

} int empty(linkstack top) { if(top->next==NULL) return 1; else return 0; } int get(linkstack top,int *e) { lnode *p; p=top->next; if(!p) { cout<<"栈已空!"; return 0; } else { *e=p->data; return 1; } } int push(linkstack top,int e) { lnode *p; if( (p=(linkstack)malloc(sizeof(lnode)))==NULL )//(给*top分配一个存储空间让top指向这个空间) { printf("分配内存失败"); exit(-1); return 0; } p->data=e; p->next=top->next; top->next=p; return 1; } int pop(linkstack top,int *e) { linkstack p=top->next; if(p==NULL) { cout<<"栈已空!"; return 0; } top->next=p->next; *e=p->data; free(p); return 1;} int length(linkstack top) { int i=0; lnode *p=top; while(p->next!=NULL) { p=p->next; i++; } return i; } void clear(linkstack top) { lnode *p,*q; p=top; while(!p) { q=p; p=p->next; free(q); } } int main() { linkstack s; lnode *p; int i; int a[]={1,2,3,4,5}; int e; init(&s); cout<<"将12345依次入栈!"<

cout<<"栈顶元素为:"; if(get(s,&e)==0) { cout<<"栈为空"; return 0; } else { cout<

友情链接:

Copyright © 2022 神龙网游活动站 - 新版本&限时福利聚合 All Rights Reserved.