有两个栈A,B分别储存一个升序数列,现要求编写算法把这两个栈中的数合成一个升序队列用c语言描述
时间: 2023-06-08 21:03:38 浏览: 155
C语言用两个栈实现一个队列的功能
5星 · 资源好评率100%
以下是代码实现:
```
#include <stdio.h>
#define MAX_SIZE 100
void mergeStacks(int stackA[], int topA, int stackB[], int topB, int mergedStack[]) {
int i = 0, j = 0, k = 0;
while (i <= topA && j <= topB) {
if (stackA[i] < stackB[j]) {
mergedStack[k++] = stackA[i++];
} else {
mergedStack[k++] = stackB[j++];
}
}
while (i <= topA) {
mergedStack[k++] = stackA[i++];
}
while (j <= topB) {
mergedStack[k++] = stackB[j++];
}
}
int main() {
int stackA[MAX_SIZE], stackB[MAX_SIZE], mergedStack[MAX_SIZE * 2];
int topA = -1, topB = -1;
int n, m;
printf("Enter the size of stack A: ");
scanf("%d", &n);
printf("Enter the elements of stack A in ascending order: ");
for (int i = 0; i < n; i++) {
scanf("%d", &stackA[++topA]);
}
printf("Enter the size of stack B: ");
scanf("%d", &m);
printf("Enter the elements of stack B in ascending order: ");
for (int i = 0; i < m; i++) {
scanf("%d", &stackB[++topB]);
}
mergeStacks(stackA, topA, stackB, topB, mergedStack);
printf("The merged stack in ascending order is: ");
for (int i = 0; i <= topA + topB + 1; i++) {
printf("%d ", mergedStack[i]);
}
return 0;
}
```
阅读全文