【问题标题】:implementing a stack using a link-list in c++在 C++ 中使用链接列表实现堆栈
【发布时间】:2016-11-18 16:15:04
【问题描述】:

我已经编写了一个将节点推入堆栈的代码,并且我已经使用单链表实现了它。但是每当我运行它时,它都会显示运行时错误。请帮帮我。

#include <iostream>
#include <string>
using namespace std;

struct node{
    int key;
    node *next;
}*head=NULL;

void push(node *n){
   n->next=head->next;
   head->key=n->key;
   head->next=n;
   cout<<head->key<<" ";
}

int main(){
   node *x;

   cin>>x->key;
   push(x);

   return 0;
}

我正在使用 C++ 4.9.2 (GCC-4.9.2) 请帮助我找出我哪里出错了

【问题讨论】:

  • UB,x 不指向任何东西。

标签: c++ pointers linked-list stack


【解决方案1】:

您重复分配内存只为指向node 的指针,而不是为node 本身:

1。你的声明

    struct node{
        int key;
        node *next;
    }*head=NULL;

只为指针head分配内存(并用值NULL对其进行初始化)。

用这个代替它:

    struct node{
    int key;
    node *next;
    }some_node, *head=&some_node;    // Allocates memory for node and for pointer, too

2。同样,您的声明:

    node *x;

只为指针x分配内存。

改用这个:

    node other_node;             // Allocate memory for the struct node 
    node *x = &other_node;       // Allocate memory for the pointer and initialize it 

【讨论】:

    猜你喜欢
    • 2012-05-24
    • 2019-03-04
    • 2020-01-16
    • 1970-01-01
    • 2011-07-29
    • 2015-05-15
    • 1970-01-01
    相关资源
    最近更新 更多