Home > OS >  i had created an program to create a linked list and insert an array in it. but it's not giving
i had created an program to create a linked list and insert an array in it. but it's not giving

Time:09-06

#include <iostream>

using namespace std;

//node 
class node {
    public:
    int data;
    node *next;
} *head = nullptr;

//function to insert array in linkedlist
void create(int A[], int n) {
    node *head = new node;
    node *temp;
    node *last;
    head->data = A[0];
    head->next = nullptr;
    last = head;
    for (int i = 1; i < n; i  ) {
        //temp is an temporary variable which creates each time and last remebers its position
        temp = new node;
        temp->data = A[i];
        cout << temp->data << endl;
        temp->next = nullptr;
        last->next = temp;
        last = temp;
    }
}

//function to display linked list which can access head because it is global
void display() { 
    node *p = head;
    while (p != nullptr) {
        cout << p->data << endl;
        p = p->next;
    }
}

int main() {
    int A[] = {1, 6, 9, 4, 5, 6};
    node *head;
    create(A, 6);
    display();
    return 0;
}

maybe i understand something wrong like to add display function in class . but i had never seen a class pointer having functions. this is my first linked list program if you want to share some good info about it please share

CodePudding user response:

The problem is that you have multiple variables named head being used for different purposes. You have a global variable head, which your display() function uses, but your create() function does not populate. create() populates a local variable named head instead, which shadows the global variable. display() never sees the created list. And main() has its own local variable named head, which is not being used for anything at all.

Get rid of the global variable. Make create() return the list it creates. And then make main() pass that list to display().

Try something like this:

#include <iostream>
using namespace std;

//node 
class node {
public:
    int data;
    node *next;
};

//function to insert array in linkedlist
node* create(int A[], int n) {
    node *head = nullptr;
    node **p = &head;
    for (int i = 0; i < n; i  ) {
        *p = new node{ A[i], nullptr };
        p = &((*p)->next);
    }
    return head;
}

//function to display linked list
void display(const node *head) { 
    node *p = head;
    while (p != nullptr) {
        cout << p->data << endl;
        p = p->next;
    }
}

//function to destroy linked list
void destroy(node *head) {
    node *p = head;
    while (p != nullptr) {
        node *next = p->next;
        delete p;
        p = next;
    }
} 

int main() {
    int A[] = {1, 6, 9, 4, 5, 6};
    node *head = create(A, 6);
    display(head);
    destroy(head);
    return 0;
}
  •  Tags:  
  • c
  • Related