Search code examples
c++linked-listinfinite-loop

Infinite looping when inserting an item into a linked list


Trying to insert a value into a linked list, but it enters an infinite loop when it is passed through the 2nd time. Been scratching my head for an hour for this problem. Is it due to variable placement issues or just algorithm in general?

Edit 1: Changed NULL to nullptr, created a counter that tells the value of karak each loop

#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";
    }

}

Solution

  • Object need to be created inside the loop to prevent the list from becoming a circular linked list. So I added list = new List(); inside the loop so the program can create the objects inside the loop.

    #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";
        }
    
    }