Ibrahim
Ibrahim

Reputation: 55

Only Printing the First Value of Linked List

I have no idea why display function is not displaying anything other than the first node's data. I've tried switching the While(p!=NULL) to while(p->next!= NULL but when I do that instead of only the first node's data displaying no data is being displayed.

#include <iostream>

using namespace std;

class Node {
public:
    int no;
    Node* next;

};


Node* createNode(int no1) {
    Node* n = new Node();
    n->no = no1;
    n->next = NULL;
    return n;
}


void addValue(int x, Node** head) {
    //insert first node into linked list

    Node* n = createNode(x),*p = *head;

        if (*head == NULL) {
            *head = n;
            
        }
        

    //insert second node onwards into linked list
    else {
    
            while (p->next!= NULL) {
                p->next = n;
                p = p->next;

            }

    }
}

void display(Node *head) {
    Node* temp = head;
    // temp is equal to head
    while (temp->next!=NULL) {
        cout << temp->no;
        temp = temp->next;
    }
}


int main() {
    int num; char choice;

    Node* head = NULL;

    do {
        cout << "Enter a number : ";
        cin >> num;
        addValue(num,&head);
            cout << "Enter [Y] to add another number : ";
        cin >> choice;
    } while (choice == 'Y');

    cout << "List of existing record : ";
    display(head);
    return 0;
}

I've tried changing the contents fo the else while loop in the addRecord function to p = p->next; p->next = n; in that order to no avail.

Upvotes: 0

Views: 354

Answers (1)

arunppsg
arunppsg

Reputation: 1563

In the while loop, it should be

while (p->next!= NULL) {
  p = p->next;
}

p->next = n;

Traverse until the end of linked list is reached and then, add the new entry.

Upvotes: 1

Related Questions