首页 > 解决方案 > 使用数组实现堆栈

问题描述

我正在尝试用 C 中的数组实现堆栈。但我猜我的推送功能不正确。(也许还有其他一些错误)因为当我运行代码时,它会打印“堆栈为空!” 两次。

我该如何解决这个问题,这个实现逻辑是否正确?

#include <stdio.h>

#define SIZE 10

 typedef struct stack
 {
     int top;
     int items[SIZE];
 }stack;

 void push(int a, stack st)
 {
     if((st.top + 1) != SIZE)
     {
         st.top++;
         st.items[st.top] = a;
     }
     else
     {
         printf("\nStack is full!");
     }
 }

 void pop(stack st)
 {
     if(st.top != -1)
     {
         st.top--;
     }
     else
     {
         printf("\nStack is empty!");
     }
 }

 void printList(stack st)
 {
     int i;
     for(i = 0; i < st.top + 1; i++)
     {
         printf("%d -> ", st.items[i]);
     }
     puts("");
 }

 int main(void)
 {
     stack stack1;
     stack1.top = -1;

     stack stack2;
     stack2.top = -1;

     push(3, stack1);
     push(5, stack1);
     push(7, stack1);

     printList(stack1);

     pop(stack1);
     printList(stack1);

     pop(stack1);
     printList(stack1);
 }

标签: cdata-structuresstack

解决方案


嗨,您的堆栈实现是错误的。使用 gdb 您可以验证这一点。您将结构作为值传递,您应该将其作为地址传递

在 gdb 上你可以看到

在主 gdb) p &stack1 $4 = (stack *) 0x7fffffffddf0

在推 fn

(gdb) p &st $3 = (堆栈 *) 0x7fffffffdd90

两者都是不同的。

正确的代码如下。

#include <stdio.h>

#define SIZE 10

typedef struct stack
{
        int top;
        int items[SIZE];
}stack;

void push(int a, stack *st)
{
        if((st->top + 1) != SIZE)
        {
                st->top++;
                st->items[st->top] = a;
        }
        else
        {
                printf("\nStack is full!");
        }
}

void pop(stack *st)
{
        if(st->top != -1)
        {
                st->top--;
        }
        else
        {
                printf("\nStack is empty!");
        }
}

void printList(stack *st)
{
        int i;
        for(i = 0; i < st->top + 1; i++)
        {
                printf("%d -> ", st->items[i]);
        }
        puts("");
}

int main(void)
{
        stack stack1;
        stack1.top = -1;

        stack stack2;
        stack2.top = -1;

        push(3, &stack1);
        push(5, &stack1);
        push(7, &stack1);

        printList(&stack1);

        pop(&stack1);
        printList(&stack1);

        pop(&stack1);
        printList(&stack1);
}

推荐阅读