列表不打印所有元素

时间:2018-03-14 14:34:56

标签: c++ linked-list

所以基本上我创建了一个包含append和prepend函数的链表,当我打印列表时,它只打印出12个我预先放在列表前面而不是其他元素,我该如何解决这个问题?这样就可以打印所有元素。我认为我的追加和前置功能是正确的,但我不知道可能出现什么问题。

#include <iostream>
#include "List.h"

using namespace std;

int main() {
    List* list = new List();
    list->Append(1);
    list->Append(2423);
    list->Prepend(12);
    list->print();
    system("pause");
    return 0;
}

#include<iostream>
#include "List.h"

using namespace std;

List::List() {
    this->HEAD = NULL;
    this->TAIL=NULL;
}
void List::Append(int Data_val) {
    NODE* Current = new NODE;
    Current->data = Data_val;

    if (HEAD == NULL) {

        HEAD = Current;
        TAIL = Current;
        Current->next = nullptr;
    }
    else {
        TAIL->next= Current;
        TAIL = Current;
        Current->next = nullptr;
    }
}
void List::Prepend(int data_val) {
    NODE* Current = new NODE;
    Current->data = data_val;
    if (HEAD = NULL) {
        Current->next = nullptr;
        HEAD = Current;
        TAIL = Current;

    }
    else {
        Current->next = HEAD;
        HEAD = Current;
        Current->next = nullptr;

    }
}
void List::print() {
    NODE* Current = HEAD;
    while (Current != NULL) {
        cout << Current->data << endl;
        Current=Current->next;
    }
}


#ifndef LIST_H
#define LIST_H

struct NODE {
    int data;
    NODE* next;
};
class List
{
    public:
        List();
        void Append(int data_val);
        void Prepend(int data_val);
        //create prepend
        //create insertafter
        //create delte
        void print();
    private:
        //
        NODE * HEAD;
        NODE* TAIL;
};
#endif

1 个答案:

答案 0 :(得分:0)

你遇到了List :: Prepand()方法的错误。 &#34;当前 - &gt; next = nullptr;&#34; 在&#34;否则&#34;中不需要行。块。

void List::Prepend(int data_val) {
    NODE* Current = new NODE;
    Current->data = data_val;
    if (HEAD == NULL) {
        Current->next = nullptr;
        HEAD = TAIL = Current;
    }
    else {
        Current->next = HEAD;
        HEAD = Current;
        Current->next = nullptr;  // <---- remove this line
    }
}