将项目插入链表时无限循环

Infinite looping when inserting an item into a linked list

尝试向链表中插入一个值,但在第二次传递时进入死循环。为了这个问题我挠了挠头一个小时。是由于变量放置问题还是一般算法?

编辑 1:将 NULL 更改为 nullptr,创建了一个计数器,告诉每个循环的 karak 值

#include <iostream>
#include <stack>
#include <string>
using namespace std;
struct List {
    char karak;
    List* next = nullptr;
};

int main()
{
    List* start = nullptr, * end = nullptr, * list = new List(), * trav = new List();
    int no = 0;
    cout << "Enter Numbers : ";
    cin >> no;
    for (int i = 0; i < no; i++) {
        trav = start;
        cout << "Enter No. " << (i + 1) << " : ";
        cin >> list->karak;
        if (i == 0) {
            start = list;
            end = list;
        }
        else {
            for (; trav->next != nullptr; trav = trav->next) { // infinite loop
                cout << "\ntest\n";
            }
            trav->next = list;
            end = list;
        }
        cout << "\n\nList Address No. " << (i + 1) << " : " << start->next << "\n\n";
        cout << "\n\nStart : " << start->karak << "\nEnd : " << end->karak << "\n\n";
    }

}

需要在循环内部创建对象,防止链表变成循环链表。所以我添加了 list = new List();在循环内,以便程序可以在循环内创建对象。

#include <iostream>
#include <stack>
#include <string>
using namespace std;
struct List {
    char karak;
    List* next = nullptr;
};

int main()
{
    List* start = nullptr, * end = nullptr, * list = new List(), * trav = new List();
    int no = 0;
    cout << "Enter Numbers : ";
    cin >> no;
    for (int i = 0; i < no; i++) {
        trav = start;
        list = new List();                      \I added here
        cout << "Enter No. " << (i + 1) << " : ";
        cin >> list->karak;
        if (i == 0) {
            start = list;
            end = list;
        }
        else {
            for (; trav->next != nullptr; trav = trav->next) { 
                cout << "\ntest\n";
            }
            trav->next = list;
            end = list;
        }
        cout << "\n\nList Address No. " << (i + 1) << " : " << start->next << "\n\n";
        cout << "\n\nStart : " << start->karak << "\nEnd : " << end->karak << "\n\n";
    }

}