简体   繁体   English

C ++指针,链接列表混乱

[英]C++ Pointers, Linked List Confusion

I am trying to build a linked list in C++. 我试图在C ++中建立一个链表。 My understanding is that the code I have created should create a node and then progressively link 4 more onto the end. 我的理解是,我创建的代码应该创建一个节点,然后逐步将4进一步链接到末尾。 Unfortunately, while I would expect to see the cout results as "12 123 1234 12345" I'm seeing "12 12 12 12" and in my main I am unable to traverse the list - it just crashes. 不幸的是,虽然我希望看到的结果是“ 12 123 1234 12345”,但我看到的是“ 12 12 12 12”,而我主要无法遍历该列表-它崩溃了。

I have the following code: 我有以下代码:

struct listNode {

    int val;
    listNode* next;

};


int nodeCount = 0;

listNode* addToEnd(listNode* node) {

    listNode* newNode = new listNode;
    newNode->val = ++nodeCount;
    newNode->next = NULL;

    if (node == NULL) {
        return newNode;
    }

    listNode* current = node;
    cout<<"\n\n";
    do {
        if (current->next == NULL) {
            current->next = newNode;
        }
        cout<<current->val<<"\n";
        current = current->next;
    } while (current->next != NULL);
    cout<<current->val<<endl;

}


int main()
{

    listNode* first = addToEnd(NULL);

    addToEnd(first);
    addToEnd(first);
    addToEnd(first);
    addToEnd(first);

    cout<<"Third: "<<first->next->next->val;

}

Any help is appreciated, as I am at wit's end! 感谢您的帮助,因为我机智极了!

It is obvious that function addToEnd is wrong 显然函数addToEnd是错误的

listNode* addToEnd(listNode* node) {

    listNode* newNode = new listNode;
    newNode->val = ++nodeCount;
    newNode->next = NULL;

    if (node == NULL) {
        return newNode;
    }

    listNode* current = node;
    cout<<"\n\n";
    do {
        if (current->next == NULL) {
            current->next = newNode;
        }
        cout<<current->val<<"\n";
        current = current->next;
    } while (current->next != NULL);
    cout<<current->val<<endl;

}

Let's assume that the list already contains two nodes and consider the do-while loop inside the function. 假设列表已经包含两个节点,并考虑函数内部的do-while循环。 At first current_next != null so the following statement is executed 首先current_next != null,因此执行以下语句

        current = current->next;

Now current points to the second node. 现在,当前指向第二个节点。 Its data member next is equal to NULL. 其数据成员next等于NULL。 So the condition of the loop 所以循环的条件

    } while (current->next != NULL);

will be false and no iteration will be repeated. 将为false,并且不会重复任何迭代。 So we added nothing. 因此,我们没有添加任何内容。

Also the function returns nothing if node is not equal to NULL. 如果node不等于NULL,该函数也不会返回任何内容。

Rewrite the function the following way 通过以下方式重写函数

listNode* addToEnd( listNode* node ) 
{

    listNode* newNode = new listNode { ++nodeCount, NULL };

    if ( node == NULL) return newNode;

    listNode* current = node;

    while ( current->next != NULL ) current = current->next;

    current->next = newNode;

    return newNode;
    // or
    //return node;    
}

Take into account that this statement 考虑到这一说法

cout<<"Third: "<<first->next->next->val;

outputs only the value of the third node. 仅输出第三个节点的值。 If you want to output all the list you should write 如果要输出所有列表,则应编写

for ( listNode *current = first; current; current = current->next ) 
{
    std::cout << current->val << ' ';
}
std::cout << std::endl;

By the way using my function you could write in main for example the following way:) 通过使用我的函数,您可以使用以下方式编写main :)

listNode* first;

addToEnd( addToEnd( addToEnd( addToEnd( first  = addToEnd( NULL ) ) ) ) );

Use a for loop to get you to the last node instead of a while, and then assign the new node OUTSIDE of the loop. 使用for循环将您带到最后一个节点(而不是一会儿),然后将新节点分配到循环的外面。 Trying to do it inside will result in an infinite loop (and make the code harder to read): 尝试在内部执行此操作将导致无限循环(并使代码难以阅读):

listNode* current;
for(current = node; current->next != NULL; current = current->next) ;
current->next = newNode;

You're also forgetting to return newNode at the end of the function. 您还忘记了在函数末尾返回newNode

You're falling off the end of a function with non- void return type. 您正在使用非void返回类型的函数结束。 The fact that you don't use the return value does not make that ok. 您不使用返回值的事实并不可行。

6.6.3 in the Standard says that: 标准中的6.6.3表示:

Flowing off the end of a function is equivalent to a return with no value; 从函数末尾流出就等于没有值的return this results in undefined behavior in a value-returning function. 这导致返回值函数中的行为不确定。

如果以if条件检查if(node==null)失败,则没有return语句。

Is it against the rules to use recursive functions in your question? 在您的问题中使用递归函数是否违反规则?

Why not do... 为什么不...

void addToEnd(listNode* node){
    if(node == NULL){
        *node = new listNode;
        node->next = NULL;
        node->val = ++nodeCount;
    }else{
        addToEnd(node->next);
    }
    return;
}

int main(){
    listNode* first = NULL;
    addToEnd(first); // 1
    addToEnd(first); // 2
    addToEnd(first); // 3
    addToEnd(first); // 4
    addToEnd(first); // Linked list is now 5 long
}

This is how I would have coded adding five nodes to a linked list that holds a node count. 这就是我要编码的方式,将五个节点添加到一个包含节点数的链表中。 If anyone has advice it is welcome. 如果有人有建议,欢迎您。

#include <iostream>
#include <cstdlib>

using namespace std;

struct listNode{
 int val;
 listNode* next;
};

listNode* addToEnd(listNode*, int);

int main()
{
  listNode* first = NULL;
  listNode* temp;
  int nodeCount = 1;

  for(int i = 0; i < 5; i++){
     first = addToEnd(first, nodeCount);
     nodeCount++;
  }

  temp = first;

  while(temp){
     cout << temp->val << ' ';
     temp = temp->next;
  }

  temp = first;
                               //Deallocate memory
  while(temp){                 //could do memory deallocation while displaying 
     nodeToDelete = temp;      //the value of nodeCount but wanted to illustrate  
                               //both methods individually
     temp = temp->next;

     delete nodeToDelete;   
  }  

  first = NULL;                //eliminate hanging pointer

  return 0;
}

listNode* addToEnd(listNode* node, int nodeCount) 
{

  listNode* newNode = new (nothrow) listNode;
  listNode* current = node;

  if(newNode){
     newNode->val = nodeCount;
     newNode->next = NULL;
     if (node == NULL)        
        node = newNode;       

     else{          
        while (current->next != NULL) 
           current = current->next;

           current->next = newNode;          
     }
  }
  else
     cout << "error allocationg memory" << endl;

  return node;
}

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

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