有 3 个堆栈 - A、B、C
堆栈 A 和 B 已排序(堆栈顶部的数字最大)。Stack C is Empty 只允许 5 次操作:
推送、弹出、顶部、is_empty、创建
我们需要编写一个函数来接收堆栈 A 和 B,将堆栈 A 和 B 中的所有数字移动到堆栈 C 并且堆栈 C 必须排序(最大的数字在顶部)。
我有算法:
比较 A 的顶部和 B 的顶部
Pop the least element and push to stack C
Repeat step 2 until any of the stack ( A or B) becomes empty
Move remaining elements from non-empty stack to C. Now you have all the elements in C but in ascending order. (That is least element at top).
Move all the elements from C to A. (Contents in A are in descending order)
Move all the elements from A to B. (Contents in B are in ascending order)
Move all the elements from B to C.
我开始编写代码但有错误,我不知道为什么!
编码 :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define MAX_MEMBERS 10
typedef struct
{
int num;
}ITEM;
typedef struct
{
ITEM a[MAX_MEMBERS];
int top;
}STACK;
void create_stack(STACK *s)
{
s->top=-1;
}
int is_empty(STACK *s)
{
return s->top==-1;
}
int is_full(STACK *s)
{
return s->top==MAX_MEMBERS-1;
}
ITEM pop(STACK *s)
{
return s->a[s->top--];
}
void (STACK *s,ITEM *item)
{
s->a[++s->top]=*item;
}
ITEM top(STACK *s)
{
return s->a[s->top];
}
void sort (STACK *a,STACK *b,STACK *c)
{
while(!is_empty(&a)||!is_empty(&b))
if(top(&a)>top(&b))
push(&c,pop(&b));
if(!is_empty(&a))
{
while(!is_empty(&a))
push(&c,pop(&a));
}
else
{
while(!is_empty(&b))
push(&c,pop(&b));
}
while(!is_empty(&c))
push(&a,pop(&c));
while(!is_empty(&a))
push(&b,pop(&a));
while(!is_empty(&b))
push(&c,pop(&b));
}
void main(void)
{
STACK a,b,c;
create_stack(&a);
create_stack(&b);
create_stack(&c);
sort(&a,&b,&c);
}