2016-11-18 174 views
-1

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

#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) 请帮我找出我错了

+3

UB,X不指向任何东西。 – Borgleader

回答

0

反复只为指针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