简体   繁体   English

使用指针在单个链表上工作

[英]using pointer to work on single linked list

This is a homework problem. 这是一个作业问题。 The program was built successful, but it can't run. 该程序已成功构建,但无法运行。 It just stopped. 才停下来 I tried to using the "struct" to make a list.I don't know what's wrong with my "insert" function. 我试图使用“结构”来列出。我不知道我的“插入”功能出了什么问题。 It's my first time here, hopefully I will get some advices. 这是我第一次来,希望我能得到一些建议。

//============================================================================
// Name        : test2.cpp
// Author      : yan zeng
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================


#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int BOOLEAN;
using namespace std;

struct Node {
    int value;
    struct Node *next;
};

void insert(int x, struct Node **pL);

void insert(int x, struct Node **pL){

    if (*pL == NULL) {
        struct Node **pL = (struct Node **) malloc(10 * sizeof(int *));

        (**pL).value = x;
        (*pL)->next = NULL;

    }

    else
        insert(x, &((*pL)->next));

}



int main (int argc, char **argv)
{

    // insert code here...

    //    make a list by declaring a pointer to a node

    struct Node *NodePointer = NULL;



    for (int i=3; i<20; i+=2) {
        insert(i,&NodePointer);
    }



}

The best advice I can give you is to learn how to use a debugger. 我能给您的最佳建议是学习如何使用调试器。 Other advice: don't use malloc/free in C++, use new/delete . 其他建议:不要在C ++中使用malloc/free ,而应使用new/delete

There is quite a few issues in this code, the use of a debugger will definitely help here. 这段代码中有很多问题,使用调试器无疑会有所帮助。

Your program "just stops" because it crashes at 您的程序“停止”,因为它在崩溃

(**pL).value = x;

I am not sure if this code was provided to you as homework to fix, or if the empty function was provided to you, and you need to fill it out. 我不确定是否将此代码作为作业提供给您进行修复,或者是否提供了空函数,是否需要填写。 Either way, that line is wrong. 无论哪种方式,那条线都是错误的。

Also, as others mentioned, you are using malloc in a C++ program when you should be using new . 另外,正如其他人提到的,当您应该使用new时,您正在C ++程序中使用malloc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM