排序堆栈时无输入

时间:2013-05-20 22:27:58

标签: arrays sorting struct stack

有3个堆栈 - A,B,C

堆栈A和B已排序(堆栈顶部的数字最大)。堆栈C为空仅允许5个操作:

push,pop,top,is_empty,create

我们需要编写一个接收堆栈A和B的函数,将堆栈A和B中的所有数字移动到堆栈C,堆栈C必须排序(最大数字在顶部)。

我有算法:

>

Compare top of A with top of B

弹出最小元素并推送到堆栈C

重复步骤2,直到任何堆栈(A或B)变空

将剩余的元素从非空堆栈移动到C.现在,C中的所有元素都按升序排列。 (这是最重要的元素)。

将所有元素从C移动到A.(A中的内容按降序排列)

将所有元素从A移动到B.(B中的内容按升序排列)

将所有元素从B移动到C.

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define MAX_MEMBERS 4
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 push(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)
{
int i;
    ITEM y,x;
    while(!is_empty(a)||!is_empty(b))
    {

y=top(a);
x=top(b);

  if(&y>&x)
   {
    push(c,&x);
    pop(b);
   }
  else
    {
     push(c,&y);
         pop(a);

    }
}
if(!is_empty(a))
{
while(!is_empty(a))
x=pop(a);
push(c,&x);
}

else
while(!is_empty(b))
{
x=pop(b);
push(c,&x);
}

while(!is_empty(c))
{
x=pop(c);
push(a,&x);
}

while(!is_empty(a))
{
x=pop(a);
push(b,&x);
}

while(!is_empty(b))
{
x=pop(b);
push(c,&x);
}

for(i=0;i<MAX_MEMBERS-1;i++)
printf("%d",c->a[i]);
}

void main(void)
{
 int i;
STACK a,b,c;
ITEM x;
create_stack(&a);
create_stack(&b);
create_stack(&c);

 for(i=0;i<4;i++)
 {
printf("\nEnter a number to insert for A: ");
scanf("%d",&x.num);
push(&a,&x);
 }

 for(i=0;i<4;i++)
 {
printf("\nEnter a number to insert for B: ");
scanf("%d",&x.num);
push(&b,&x);
 }

    sort(&a,&b,&c);

}

我调试了代码并查看了问题所在.. 它在这里:if(&amp; y&gt;&amp; x) 它始终为此布尔条件赋予“true”值。 即使是x

1 个答案:

答案 0 :(得分:0)

因为你比较变量的地址,而不是变量本身