【问题标题】:pop() method of stack linked list using C has an error使用C的栈链表的pop()方法有错误
【发布时间】:2018-11-26 10:43:25
【问题描述】:

问题是printf()pop() 方法中显示奇怪的地址并且不再运行。打印结果如下。

push (10)
push (20)
push (30)
push (40)
40
-842150451

这是完整的代码。

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

typedef struct node{
    int data;
    struct node *next;
}node;

node* head = NULL;

void init(){
    head = (node*)malloc(sizeof(node));
    head->data = 0;
    head->next = NULL;
}

void push(int data){

    node* temp = (node*)malloc(sizeof(node));
    if(temp == NULL){
        printf("Out Of Memory");
    }else{
        head = (node*)malloc(sizeof(node));
        temp->data = data;
        temp->next = head;
        head = temp;
        printf("push (%d)\n", data);
    }
}

void pop(){
    node* temp;
    if(head == NULL) return;
    temp = head;
    printf("%d\n", head->data);
    head = head->next;
    free(temp);
}

void main(){

    push(10);
    push(20);
    push(30);
    push(40);

    pop();
    pop();
    pop();
    pop();
}

而且这个 pop 方法不起作用。 第一次显示40。

然后打印 -842150451。 我不明白为什么我会收到这个奇怪的号码。

void pop(){
    node* temp;
    if(head == NULL) return;
    temp = head;
    printf("%d\n", head->data);
    head = head->next;
    free(temp);
}

【问题讨论】:

    标签: c data-structures linked-list stack


    【解决方案1】:

    push() 中有一个奇怪的额外 malloc,我把它去掉了,看起来好多了:

    void push(int data) {
    
        node* temp = (node*)malloc(sizeof(node));
        if (temp == NULL) {
            printf("Out Of Memory");
        } else {
            //head = (node*)malloc(sizeof(node));     <---- this is your problem
            temp->data = data;
            temp->next = head;
            head = temp;
            printf("push (%d)\n", data);
        }
    }
    
    
    push (10)
    push (20)
    push (30)
    push (40)
    40
    30
    20
    10
    

    【讨论】:

    • 哦,天哪!所以谢谢!当我通过您的回答注意到我的问题时。我觉得自己很愚蠢。我想我没有很好地理解逻辑。但现在清楚了。非常感谢!
    • 别担心...动态内存一开始可能是一个棘手的概念,但看起来您已经掌握了窍门。
    猜你喜欢
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2018-09-02
    • 2016-10-15
    • 2016-07-27
    • 2023-03-20
    • 2012-09-30
    相关资源
    最近更新 更多