- 前面介绍的栈的实现可以用于实现单个栈,并且实现栈的操作,接下来介绍多重栈的实现,也就是一次向创建
N
个栈用于模拟栈的功能,并且实现相关操作; - 多重栈的实现最重要的实现实现通过下标对于各个栈的访问,也就是需要通过数组下标的方式来随机性的访问各个栈;
- 首先需要定义一个数组来进行栈的下标随机访问;
StackNode top[MAX_SIZE] = {NULL};
* 通过top
的下标完成栈的随机访问工作;
* 元素的添加操作,这里就需要指定添加栈元素的下标;
void push(int i, elements item)
{
StackNode temp = (StackNode)malloc(sizeof(StackNode));
if (temp == NULL)
{
fprintf(stderr, "malloc is error\n");
exit(EXIT_FAILURE);
}
temp->data = item;
temp->link = top[i];
top[i] = temp;
}
- 元素的弹出操作,同样需要指定栈的下标;
elements pop(int i)
{
StackNode temp = top[i];
elements item;
if (!temp)
exit(EXIT_FAILURE);
item = temp->data;
top[i] = temp->link;
free(temp);
return item;
}
* 打印操作,用来检验栈里面的元素添加是否正常;
void StackPrint(int i)
{
if (i < 0 || i > MAX_SIZE)
{
fprintf(stderr, "The number out of range\n");
exit(EXIT_FAILURE);
}
printf("The Stack[%d] Contains:\n", i);
StackNode temp = top[i];
while (temp != NULL)
{
printf("[%d]\n", temp->data.key);
temp = temp->link;
}
}
- 访问栈顶指针操作
elements stacktop(int i){
StackNode temp=top[i];
if(!temp)
exit(EXIT_FAILURE);
return temp->data;
}
- 弹出元素操作
void pop(int i)
{
StackNode temp = top[i];
elements item;
if (!temp)
exit(EXIT_FAILURE);
item = temp->data;
top[i] = temp->link;
free(temp);
}
- 完整的程序代码
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 10
typedef struct
{
int key;
} elements;
typedef struct node *StackNode;
struct node
{
elements data;
StackNode link;
};
StackNode top[MAX_SIZE] = {NULL};
void push(int i, elements item)
{
StackNode temp = (StackNode)malloc(sizeof(StackNode));
if (temp == NULL)
{
fprintf(stderr, "malloc is error\n");
exit(EXIT_FAILURE);
}
temp->data = item;
temp->link = top[i];
top[i] = temp;
}
void pop(int i)
{
StackNode temp = top[i];
elements item;
if (!temp)
exit(EXIT_FAILURE);
item = temp->data;
top[i] = temp->link;
free(temp);
}
elements stacktop(int i){
StackNode temp=top[i];
if(!temp)
exit(EXIT_FAILURE);
return temp->data;
}
void StackPrint(int i)
{
if (i < 0 || i > MAX_SIZE)
{
fprintf(stderr, "The number out of range\n");
exit(EXIT_FAILURE);
}
printf("The Stack[%d] Contains:\n", i);
StackNode temp = top[i];
while (temp != NULL)
{
printf("[%d]\n", temp->data.key);
temp = temp->link;
}
}
int main()
{
elements item;
item.key = 10;
int num;
num = 1;
push(num, item);
push(num, item);
push(num, item);
push(num, item);
StackPrint(1);
num = 2;
push(num, item);
StackPrint(2);
return 0;
}
- 程序执行结果截图: