多栈运算

来源:互联网 发布:国际贸易统计数据库 编辑:程序博客网 时间:2024/04/24 10:13

多栈运算的算法思想:将多个链栈的栈顶指针放在一个一维指针数组中来统一管理,从而实现同时管理和使用多个栈。

wKioL1c0jzjBUGYkAAAjsxAXniU553.png

多链栈示意图


实现代码如下:

#include<iostream>

using namespace std;

#define TRUE 1

#define FALSE 0

#define M 10

typedef struct node

{

int data;

struct node *next;

}LinkStackNode, *LinkStack;

LinkStack top[M];


//第i号栈进栈操作

int Pushi(LinkStack top[M], int i,int x)//将元素x进入第i号链栈

{

LinkStackNode *temp;

temp = (LinkStackNode *)malloc(sizeof(LinkStackNode));

if (temp==NULL)//申请空间失败

{

return FALSE;

}

temp->data= x;

temp->next = top[i]->next;

top[i]->next = temp;//修改当前栈顶指针

return TRUE;

}


//第i号栈出栈操作

int Pop(LinkStack top[M], int i,int *x)//将第i号栈的栈顶元素弹出,放到x所指的存储空间中

{

LinkStackNode *temp;

temp = top[i]->next;

if (temp == NULL)//第i号栈为空栈

{

return FALSE;

}

top[i]->next = temp->next;

*x=temp->data ;

free(temp);//释放存储空间

return TRUE;

}


本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1772840

0 0
原创粉丝点击