为什么头值不是"NULL"?

Nih*_*har 0 c++ linked-list

试图找出链接列表问题.遇到这个基本错误在createLinkList()中头部值不是"NULL".我在这里缺少什么诀窍.这是我的代码.

#include <iostream>
using namespace std;

void createLinkList(struct node**);
void showList();
void insertNode();

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

int main()
{
    struct node* head = NULL;
    createLinkList(&head);
    cout<<"inside main function \t"<<head<<endl;
    return 0;
}
void createLinkList(struct node **head){
    int data;
    struct node * new_node;

    cout<<"creating Link List ..."<<endl;
    cout<< "Enter the data to be inserted"<<endl;
    cin >> data;
    cout<<"inside createLinkList \t"<<head<<endl;
    if (head == NULL){
        new_node->data=data;
        new_node->next=*head;
        *head=new_node;
        cout<<"Element Added at Head Position"<<endl;
    }
    else{
        cout<<"Element added at other positions"<<endl;
    }

}
Run Code Online (Sandbox Code Playgroud)

输出: 在此输入图像描述

无法理解为什么head()和createLinkList()中的头值不同.

Joh*_*ger 5

你的createLinkList方法没有head指针,它正在pointer-to-head指针.它应该被称为pHead:

void createLinkList(struct node **pHead){
Run Code Online (Sandbox Code Playgroud)

所以,你head将永远不会NULL-你应该是什么测试是否*headNULL.

但是你有更多的问题.你没有创建new节点!

你的代码说(没有调试行):

struct node * new_node;    // <<< You probably want new_node = new node;

if (head == NULL){         // <<< You definitely want *head here!
    new_node->data=data;   // <<< This variable is uninitialised
    new_node->next=*head;  // <<< You know this is NULL - the if said so
    *head=new_node;
Run Code Online (Sandbox Code Playgroud)

简而言之,您需要回到绘图板.