数据结构-栈的链式表示(指针双星问题**prt)

实现简单,主要是搞清楚,当指针作为参数的时候,如何在函数值对行参进行修改 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

*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值