【问题标题】:Sorting two stacks by using structs - compile error使用结构对两个堆栈进行排序 - 编译错误
【发布时间】:2013-05-25 17:53:20
【问题描述】:

有 3 个堆栈 - A、B、C

堆栈 A 和 B 已排序(堆栈顶部的数字最大)。 Stack C is Empty 只允许 5 次操作:

推送、弹出、顶部、is_empty、创建

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

我有算法:

比较 A 的顶部和 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 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);
}

【问题讨论】:

  • C 将按降序而不是升序..因为当您弹出 C 时它将按降序排列
  • 排序算法也不正确。

标签: c sorting stack


【解决方案1】:

有一堆错误,其中很多归结为push签名:

void push(STACK s,int item)

看起来应该是这样的:

void push(STACK *s,int item)

其余的归结为不将STACK 结构的地址传递给您的函数,例如:

push(a,x);

应该是:

push(&a,x);

另外main 应该总是返回int

int main()

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 2015-01-14
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2019-05-05
    • 2020-12-04
    相关资源
    最近更新 更多