实现简单,主要是搞清楚,当指针作为参数的时候,如何在函数值对行参进行修改 st. 调用函数处传入的参数同时修改。
#include<iostream>
#include<stdlib.h>
#define OK 1
#define ERROR 0
using namespace std;
typedef struct Stack_Node
{
int data;
struct Stack_Node *next;
}Stack_Node;
int init_stack(Stack_Node **top,Stack_Node **bottom)
{
*bottom=*top=(Stack_Node*)malloc(sizeof(Stack_Node));
if(!*top) return ERROR;
(*top)->next=NULL;
return OK;
}
int insert_stack(Stack_Node **top,int num)
{
Stack_Node *s;
s=(Stack_Node*)malloc(sizeof(Stack_Node));
if(!s) return ERROR;
s->data=num;
//cout<<"上一个元素是:"<<(*top)->data<<endl;
s->next=(*top)->next;
(*top)->next=s;
(*top)=s;
//cout<<"函数中修改地址"<<(*top)<<endl;
return OK;
}
int pop_stack(Stack_Node **bottom,Stack_Node **top,int *num)
{
Stack_Node *p,*q;
if((*bottom)->next==NULL) return ERROR;
q=(*bottom);
p=(*bottom)->next;
while(p->next!=NULL)
{
q=p;
p=p->next;
}
q->next=p->next;
*num=p->data;
free(p);
*top=q;
return OK;
}
int show_stack(Stack_Node *bottom)
{
if(bottom->next==NULL) return ERROR;
Stack_Node *p;
p=bottom->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
return OK;
}
int main()
{
Stack_Node *top=NULL,*bottom=NULL;
if(!init_stack(&top,&bottom)) cout<<"初始化失败"<<endl;
while(1)
{
cout<<"压栈1弹栈2输出3"<<endl;
int tmp;
cin>>tmp;
switch(tmp)
{
case 1:
int num;
cin>>num;
//cout<<"调用之前top地址"<<top<<endl;
if(!insert_stack(&top,num))
{
cout<<"压栈失败"<<endl;
}
//cout<<"调用之后top地址"<<top<<endl;
break;
case 2:
int data;
if(!pop_stack(&bottom,&top,&data))
{
cout<<"弹栈失败"<<endl;
}
else
{
cout<<"弹出元素:"<<data<<endl;
}
break;
default:
if(!show_stack(bottom)) cout<<"空栈"<<endl;
break;
}
}
return 0;
}
/*
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
1
56
1
4568
1
569
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
1
56
1
45
1
59
3
*/