typedef struct stacknode
{
int data;
struct stacknode *next;
}stacknode,*stacklist;
stacknode *p和stacklist p是等价的,stacknode是个 struct 的tag struct stacknode 才形成一个 type , 经过 typedef struct stacknode { ... } stacknode; 之后 stacknode等同于 struct node.
#include <iostream>
#include<malloc.h>
#include<stdio.h>using namespace std;
int maxsize = 100;
typedef struct sqstack
{
int *base;
int *top;
int stacksize;
}sqstack;
bool init(sqstack &s)//初始化栈
{
s.base = new int(maxsize);
if(!s.base)
return false;
s.top = s.base;
s.stacksize = maxsize;
return true;
}
bool pushstack(sqstack &s)//压入栈
{
if(s.top-s.base==maxsize)
return false;
int n;
cout<<"输入入栈元素个数"<<endl;
cin>>n;
int e;
for(int i= 0;i<n;i++){
cin>>e;
*s.top++=e;//先赋值,指针加一
}
return true;
}
int outstack (sqstack &s)//出栈
{
int e;
if(s.base == s.top)
return 0;
e=*--s.top;
return e;
}
int popstack(sqstack &s)//取栈顶元素
{
if(s.top!=s.base)
{
return *(s.top-1);
}
}
int main()
{
sqstack s;
int e;
init(s);
pushstack(s);
int ans = outstack(s);
int ans1 = popstack(s);
cout<<ans<<endl<<ans1;
return 0;
}
#include<stdio.h>
#include<iostream>
#include<stack>
#include<malloc.h>
using namespace std;
typedef struct stacknode
{
int data;
struct stacknode *next;
}stacknode,*stacklist;
void init(stacklist s)//初始化
{
s = (stacklist)malloc(sizeof(stacklist));
s->next=NULL;
}
int emptystack(stacklist s)
{
if(s->next==NULL)
return 1;
return 0;
}
int pushstack(stacklist s)
{
stacklist p;
// p=(stacklist)malloc(sizeof(stacklist));
// if(p==NULL)
// return 0;
cout<<"输入入栈的个数"<<endl;
int n ;
cin>>n;
int e;
for(int i = 0;i < n;i++)
{
cout<<"输入元素"<<endl;
p=(stacklist)malloc(sizeof(stacklist));
cin>>e;
p->data = e;
p->next= s->next;
s->next = p;
}
return 1;
}
int popstack(stacklist s,int *e)
{
stacknode *temp;
if(emptystack(s))
return 0;
temp = s->next;
*e = temp->data;
s->next = temp->next;
free(temp);
return *e;
}
int main()
{
int e;
stacknode s;
init(&s);
pushstack(&s);
cout<<"弹出的元素为:";
cout<<popstack(&s,&e)<<endl;
cout<<"弹出的元素为:";
cout<<popstack(&s,&e);
return 0;
}