I had created a program to create a linked list and insert an array in it. But it's not giving the desired output, may be the problem is in display function
#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 could share some good info about it please do, thank you
node *head= new node;declares a new local variable that hides the global variablehead. See e.g. learncpp.com/cpp-tutorial/variable-shadowing-name-hidingnodewith a constructor, destructor, and usefully in this case, an append (or prepend) member function. C++ makes this possible. What's shown is basically C with iostream.