簡體   English   中英

打印功能不會終止

[英]Print function doesn't terminate

我不知道為什么PrintList()不終止。 它是一個LinkedList,因此當我轉到下一個時,該列表應該終止。 當我執行一次AddNode然后打印時,該操作終止,當我執行兩次addNode時,打印不會終止。

在構造函數中創建5個空白點的原因是因為程序啟動時需要創建這5個空白點。

而且,例如,如果我加了兩次,如何將指針分配給第二個值?

#pragma once
class LinkedList
{
private:
    typedef struct node {
        int data;
        node* next;
    }* nodePtr;

    nodePtr n;

    nodePtr head;
    nodePtr curr;
    nodePtr temp;
public:
    LinkedList();
    void AddNode(int addData);
    void PrintList();
    ~LinkedList();
};

#include "LinkedList.h"
#include<cstdlib>
#include<iostream>
using namespace std;


LinkedList::LinkedList()
{
    head = NULL;
    curr = NULL;
    temp = NULL;

    n = new node;

    for (int x = 1; x <= 5; x++) {
        //cout << n<<endl;
        n->next = n;
    }

}

void LinkedList::AddNode(int addData) {
    //nodePtr n = new node;
    n->next = NULL;
    n->data = addData;
    cout << n <<endl;
    if (head != NULL) {
        curr = head;
        while (curr->next != NULL) {
            curr = curr->next;
        }
        curr->next = n;
    }
    else {
        head = n;
    }
}


void LinkedList::PrintList() {
    curr = head;
    while (curr != NULL) {
        cout << curr->data << endl;
        curr = curr->next;
    }

}


LinkedList::~LinkedList()
{
    head = NULL;
    curr = NULL;
    temp = NULL;
    delete n;
}

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include "LinkedList.h"
using namespace std;

int main() {
    LinkedList *l = new LinkedList();
    l->AddNode(5);
    l->AddNode(8);
    l->PrintList();
    system("pause");
    return 0;
}

節點n總是相同的,因為您沒有將n設置為其他節點,所以當您執行n-> next和n-> data時,每次都修改同一節點

 void LinkedList::AddNode(int addData) { //nodePtr n = new node; // you need to uncomment this n->next = NULL; n->data = addData; cout << n <<endl; if (head != NULL) { curr = head; while (curr->next != NULL) { curr = curr->next; } curr->next = n; } else { head = n; } } After your first addNode(5), lets examine the values. head = n head->data = 5 head->next = null After your second addNode(8) head = n head->data = 8 head->next = n // set by "curr->next = n" . 

所以你在這里有問題。 當您嘗試遍歷鏈接列表時,它將變成head-> next-> head-> next-> head-> next-> head-> next .....導致無限循環

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM