0
有3個棧 - A,B,C通過使用結構排序兩個堆棧 - 編譯錯誤
堆棧A和B被排序(在堆棧的頂部的數目是最大的)。堆棧C是空的,只有5操作被允許:
PUSH,POP,頂部,is_empty,創建
我們需要寫接收棧A和B的功能,在棧A和B移動所有的號碼堆棧C和堆棧C必須被排序(最大的數字在最上面)。
我有算法:
比較A的頂部與B的頂部
彈出的最小元素和推到堆棧Ç
重複步驟2,直到任何疊層的(A或B )變爲非空棧空
移動剩餘的元素C.現在,你必須在C,但按升序排列的所有元素。 (這是最上面的元素)。
移動所有的從C到A.元件(在內容是按降序排列)
全部移動從A元素B.(B中的內容是按升序排列)
全部移動從B到C.
和元素我開始寫代碼,但有錯誤,我不知道爲什麼!
代碼:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define MAX_MEMBERS 8
typedef struct
{
int x[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;
}
int pop(STACK *s)
{
return s->x[s->top--];
}
void push(STACK *s,int item)
{
s->x[++s->top]=item;
}
int top(STACK *s)
{
return s->x[s->top];
}
void ex1(STACK *a, STACK *b)
{
STACK c;
while(!is_empty(a)&&!is_empty(b))
{
if(top(&a)>top(&b))
push(&c,pop(&a));
else if(top(&a)<top(&b))
push(&c,pop(&b));
else
{
pop(&a);
push(&c,pop(&b));
}
}
if(is_empty(&a))
while(!is_empty(&b))
push(&c,pop(&b));
else while(!is_empty(&a))
push(&c,pop(&a));
while(!is_empty(&c))
push(&a,pop(&c));
while(!is_empty(&a))
push(&b,pop(&a));
while(!is_empty(&b))
push(&c,pop(&b));
}
main()
{
STACK a,b;
int i,x;
create_stack(&a);
create_stack(&b);
for(i=0;i<4;i++)
{
printf("enter a num for stack a :\n");
scanf("%d",&x);
push(&a,x);
printf("enter a num for stack b :\n");
scanf("%d",&x);
push(&b,x);
}
ex1(a,b);
}
,並且錯誤是? – mwerschy
我編輯了代碼.. –
'C'會按降序排列,而不是升序.cuz當你彈出'C'時它會以降序排列 – Anirudha