我在一个操作系统类中,我必须编写一个简单的堆栈程序(主要功能只是确定用户要求您做什么)。如果这不需要在 C 中,我很久以前就会这样做,但是因为我不太擅长 C 编码,所以它有一个“错误”......到目前为止的错误是它只是继续“弹出”相同的值关闭。 (它实际上并没有弹出任何东西)。我认为这是因为我不明白结构和指针是如何真正工作的。或者这是一个不那么明显的编码错误?

#include <stdio.h>

struct node {
    int data;
    struct node *next;
    struct node *prev;
} first;

void push(int);
void pop();

int main(void)
{
    int command = 0;

    while (command != 3)
    {
        printf("Enter your choice:\n1) Push integer\n2) Pop Integer\n3) Quit.\n");
        scanf("%d",&command);
        if (command == 1)
        {
            // push
            int num;
            scanf("%d",&num);
            push(num);
        }
        else
        {
            if (command == 2)
            {
                pop();
            }
            else
            {
                if (command != 3)
                {
                    printf("Command not understood.\n");
                }
            }
        }
    }

    return 0;
}

void push (int x)
{
    struct node newNode;
    newNode.data = x;
    newNode.prev = NULL;
    newNode.next = &first;
    first = newNode;
    printf("%d was pushed onto the stack.\n", first.data);
}

void pop()
{
    if (first.data == '\0')
    {
        printf("Error: Stack Empty.\n");
        return;
    }
    printf("%d was popped off the stack.\n", first.data);
    first = *(first.next);
    first.prev = NULL;
}

最佳答案

首先应该是一个指针。将其更改为 struct node *first

在主要初始化 first=NULL ;

改变你推送/弹出操作如下,

void push (int x)
{
    struct node *newNode;// It should be a pointer
newNode = (struct node *)malloc(sizeof(struct node));
    newNode->data = x;
    //newNode.prev = NULL; // You don't need this
    newNode->next = first;
    first = newNode;
    printf("%d was pushed onto the stack.\n", first->data);
}

void pop()
{
struct node *prevPtr;
    //if (first.data == '\0')
    if (first == NULL) // check if stack is empty
    {
        printf("Error: Stack Empty.\n");
        return;
    }

    printf("%d was popped off the stack.\n", first->data);
prevPtr = first;
    first = first->next;

free(prevPtr);
}

关于c - C中的简单堆栈程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18995071/

10-12 02:12