VVG
VVG

Reputation: 141

wrong print of linked list c++

Could you, please, explain me, why function "print" prints one same number infinitely in this code?

Apparently, linked list is constructed correctly, but while debugging step by step, it sticks on "print" function.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

struct num {
    int n;
    num* next;};

void add (num*&head, int size) {
    num*newnode = new num;
    for (int i = 0; i<size; i++) {
        newnode->n = rand()%100;
        newnode->next = head;
        head = newnode;}
}

void print (num*head) {
    num*temp = head;
    while (temp != 0) {
        cout << temp->n << endl;
        temp = temp ->next;}}

void del (num*&head) {
    num*temp = 0;
    while (head!=0){
        temp = head;
        head = head->next;
        delete temp;}}

int main () {
srand ((unsigned int)time(0));
num*head = 0;
add (head, 10);
print (head);
del (head);
cin.get();
cin.ignore();
}

Upvotes: 1

Views: 55

Answers (2)

Nikolay K
Nikolay K

Reputation: 3850

You create a loop in your list in add function

newnode->next = head;
head = newnode;

So there is only 1 node and its next points to head, and head points to this node. If you move num*newnode = new num; inside the loop you'll fix this.

Upvotes: 1

Thiyagu
Thiyagu

Reputation: 17880

The problem is in add function. You are not creating new nodes.Instead modifying the same node and pointing it to itself.

Change like this

    for (int i = 0; i<size; i++) {
        newnode = new num; //new node
        newnode->n = rand()%100;
        newnode->next = head;
        head = newnode;}

Upvotes: 2

Related Questions