栈的链式存储(利用指针来完成出入栈,i为计数器)
#include <iostream.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}stack;
#ifndef NULL
const int NULL=0;
#endif // 定义NULL常量
void main()
{
stack *top;
top=(stack*) malloc(sizeof(stack));
top->next=NULL;
//入栈
char ch;
int i=0;
while(ch!='n') //当ch不等于n时执行循环体,否则不执行
{
stack *s;
s=(stack*) malloc(sizeof(stack));
cout<<"input the data to stack:";
cin>>s->data;
i++;
s->next=top->next;
top->next=s;
cout<<"would you like to continue to push:y/n?";
cin>>ch;
}
//出栈
if(top->next==NULL) cout<<"the stack is empty!";
else
{ cout<<"top::::data"<<endl;
while (top->next!=NULL)
{
stack *p;
p=top->next;
i--;
cout<<i<<":::"<<p->data<<endl;
top->next=p->next;
free(p);
}
}
}
#include <iostream.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}stack;
#ifndef NULL
const int NULL=0;
#endif // 定义NULL常量
void main()
{
stack *top;
top=(stack*) malloc(sizeof(stack));
top->next=NULL;
//入栈
char ch;
int i=0;
while(ch!='n') //当ch不等于n时执行循环体,否则不执行
{
stack *s;
s=(stack*) malloc(sizeof(stack));
cout<<"input the data to stack:";
cin>>s->data;
i++;
s->next=top->next;
top->next=s;
cout<<"would you like to continue to push:y/n?";
cin>>ch;
}
//出栈
if(top->next==NULL) cout<<"the stack is empty!";
else
{ cout<<"top::::data"<<endl;
while (top->next!=NULL)
{
stack *p;
p=top->next;
i--;
cout<<i<<":::"<<p->data<<endl;
top->next=p->next;
free(p);
}
}
}
转载于:https://blog.51cto.com/simeixiaofeng/182105