C堆栈错误链接LIst

时间:2011-04-06 23:13:14

标签: c

存在大量错误,严重的是什么错误? 我尝试使用它没有typedef,但问题是什么?有人可以帮我调试吗?

struct node {
    int info;
    struct node *link;
};

int main (void)
{
    int choice;
    struct node *top;
    top = NULL;
    while (1) {
        printf("1.Push\n");
        printf("2.Pop\n");
        printf("3.Display\n");
        printf("4.Quit\n");
        printf("Enter your choice : ");
        scanf("%d", &choice);

        switch(choice) {
            case 1:
                push();
                break;
            case 2:
                pop();
                break;
            case 3:
                display();
                break;
            case 4:
                exit(1);
            default:
                printf("Wrong choice\n");
        }
    }
    return 0;
}

void push (void)
{
    struct node *tmp;
    int pushed_item;
    tmp = malloc(sizeof(struct node));
    printf("Input the new value to be pushed on the stack : ");
    scanf("%d", &pushed_item);
    tmp->info = pushed_item;
    tmp->link = top;
    top = tmp;
}

void pop (void)
{
    struct node *tmp;
    if (top == NULL)
        printf("Stack is empty\n");
    else {
        tmp = top;
        printf("Popped item is %d\n", tmp->info);
        top = top->link;
        free(tmp);
    }
}

void display (void)
{
    struct node *ptr;
    ptr = top;
    if (top == NULL)
     printf("Stack is empty\n");
    else {
        printf("Stack elements :\n");
        while (ptr != NULL) {
            printf("%d\n", ptr->info);
            ptr = ptr->link;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

首先,main函数必须低于它调用的函数。其次,您需要#import <stdio.h>才能使用printf。第三,top不是全局变量,所以你不能在display函数中使用它。

从那里开始工作。

答案 1 :(得分:1)

尝试将此代码段放在文件的顶部:

#include <stdio.h>
#include <stdlib.h>

void push(void);
void pop(void);
void display(void);

struct node* top; // good catch by Borealid