2016-11-18 73 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