您的位置:首页 > 其它

链栈的运算 置空/判空/进栈/出栈/读栈顶

2015-11-24 17:36 162 查看
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#define MAXSIZE 100
using namespace std;
//链栈的本质上是单链表,无非是限制了插入和删除运算只能在链头进行。
//由于在链头运算,不用像单链表那样附加头结点,更方便运算。
//链栈的类型
struct node{
int data ;
struct node *next ;

};
//由于没有对头结点指针,进行函数传递,导致代码看起来很弱,
//传入的头指针地址,返回的也是头指针地址

//链栈置空
struct node* setnull(struct node *top){

top = NULL ;
return top ;
}

//判链空
int isempty(struct node *top){
if(top == NULL)
return 1;
return 0 ;
}

//进栈
struct node * push(struct node *top ,  int x){
struct node *s = (struct node *)malloc(sizeof(struct node)) ;
s->data = x ;
s->next = top ;
top = s ;
cout<<"push () top = " << top << endl;
return top ;
}

//出栈
struct node *  pop(struct node *top){
if(top == NULL)
return NULL ; //栈为空时,返回NULL
struct node *s = top ;
top= top->next ;
free(s) ;
return top;
}

//读栈顶元素
int gettop(struct node *top){
if(top == NULL)
return NULL ;  // 栈为空时,返回NULL
return top->data ;
}
int main(){
struct node *s ;

s=setnull(s) ;
cout << "s = " << s<<endl;
for(int i =1  ;i <10 ; i++)
{
s  = push(s , i) ;
cout<< "s = "<<s << endl;
}
while(!isempty(s)){
cout<<"出栈顺序: "<<gettop(s)<<endl ;
s = pop(s ) ;
}
return 0 ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链栈的运算