-4

As we say we have to access an element in linked list sequentially. Then what is this:

  cout<<"Enter size of linked list : ";
   int n;
   cin>>n;
   node *ll[n];
   cout<<endl<<"enter elements : ";
   for(int i=0;i<n;i++)
   {
        ll[i]=new node();
        ll[i]->next=NULL;
        cin>>ll[i]->data;
   }
   for(int i=0;i<n-1;i++)
   {
        ll[i]->next=ll[i+1];
   }
   cout<<endl<<ll[1]->data;

cout<<endl<<ll[1]->data; I can access a random element with this line, right?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Please don't SHOUT — it is considered rude. – Jonathan Leffler Oct 08 '21 at 03:47
  • 1
    You're doing random access on an array — the linked list access is not used. – Jonathan Leffler Oct 08 '21 at 03:48
  • Note that it is conventional to put the `endl` at the end of an output operation, not at the start. You are using a variable-length array (VLA) at `node *ll[n];` — that is not a part of standard C++, though it is allowed by GCC (and probably by Clang too). – Jonathan Leffler Oct 08 '21 at 03:49
  • [Variable-length arrays are not part of standard C++](https://stackoverflow.com/questions/1887097/), use `std::vector` instead. – Remy Lebeau Oct 08 '21 at 04:14

1 Answers1

1

As Jonathan Leffler noted in the comments, you've created an array of nodes and linked them together, but you're not using them as a linked list, but as an array.

You could save a pointer to a given node and use that to make access slightly faster, but there's no guarantee that pointer would remain useful if the list is otherwise mutated.

Linked list access is inherently not constant-time.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Chris
  • 26,361
  • 5
  • 21
  • 42