mercredi 23 septembre 2020

Infinite Loop with C++ Linked Lists [duplicate]

I am having problems adding to and printing a singly linked list with a dummy node. The dummy node makes insertion easier. I am able to run the code and add individual nodes to the linked list. However, whenever I try to iterate through and add nodes, I get an infinite loop.

Why is the same process not working in a loop? It works perfectly out of a loop as well as in Java.

#include <iostream>
#include <string>
using namespace std;

string gen_random(const int len) {
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    string x = "";
    for (int i = 0; i < len; ++i) {
        x+= alphanum[rand() % (sizeof(alphanum) - 1)];
    }
    return x;
}

class Node {
    public:
  string data;
  int freq;
  struct Node *next;

  Node(string d, int f, Node* x){
      this->data = d;
      this->freq = f;
      this->next = x;
  }

  void print(){
      string x;
      if(next == NULL) x = "NULL";
      else x = next->data;
      cout << data << "," << freq << "," << x << " ---> ";
  }
};

class LinkedList{
    public:
        Node* head;

        LinkedList(){
            Node* dummy = new Node("dummy", 0, NULL);
            this->head = dummy;
        }

        Node* findPlace(Node n){
            Node* temp = head;
            while(temp->next != NULL && n.freq > temp->next->freq){
                temp = temp->next;
            }
            return temp;
        }
        
        void insert(Node* spot, Node n){
            n.next = spot->next;  
            spot->next = &n;  
        }

        void printList(){
            Node* temp = head;
            while(temp != NULL){
                temp->print();
                temp = temp->next;
            }
            cout << endl;
        }
};

int main() {

    /* this part works */

    LinkedList LL;
    LL.printList();
    Node* sp;

    Node r = Node("hello", 6, NULL);
    sp = LL.findPlace(r);
    LL.insert(sp, r);
    LL.printList();

    r = Node("james", 7, NULL);
    sp = LL.findPlace(r);
    LL.insert(sp, r);
    LL.printList();

    /* this loop fails */
    int i = 0;
    while(i < 100){
        r = Node(gen_random(4), i, NULL);
        sp = LL.findPlace(r);
        LL.insert(sp, r);
        LL.printList();
        i += 1;
    }
    
}

Aucun commentaire:

Enregistrer un commentaire