S
S
sabn1k2016-02-29 19:11:56
C++ / C#
sabn1k, 2016-02-29 19:11:56

How does a linked list work?

I don’t understand a little what exactly the program code is doing at this moment.

template<class TYPE>
struct link
{
  TYPE data;
  link* next;
};
template<class TYPE>
class linklist
{
private:
  link<TYPE>* first;
public:
  linklist(){ first = NULL; }
  void additem(TYPE d);
  void display() const;
};
template<class TYPE>
void linklist<TYPE>::additem(TYPE d)
{
  link<TYPE>* newlink = new link<TYPE>;
  newlink->data = d;
  newlink->next = first;
  first = newlink;
}
template<class TYPE>
void linklist<TYPE>::display() const
{
  link<TYPE>* current = first;
  while (current != NULL)
  {
    cout << endl << current->data;
    current = current->next;
  }
}

int main(int argc, char**argv)
{
  setlocale(0, "");
  linklist<double> ld;

  ld.additem(151.3);
  ld.additem(121.3);
  ld.additem(531.3);
  ld.display();

  linklist<char> lch;
  lch.additem('a');
  lch.additem('b');
  lch.additem('c');
  lch.display();
  _getch();
  return 0;
}

Namely, what is happening here:
template<class TYPE>
void linklist<TYPE>::additem(TYPE d)
{
  link<TYPE>* newlink = new link<TYPE>;
  newlink->data = d;
  newlink->next = first; // вот здесь не пойму, что именно мы записываем в next
  first = newlink; // и здесь не пойму, что именно мы присваиваем first
}
/////////////////////////////////////////////
template<class TYPE>
void linklist<TYPE>::display() const
{
  link<TYPE>* current = first; // что именно мы записываем в current?
  while (current != NULL)
  {
    cout << endl << current->data;  
    current = current->next; // и тут тот же вопрос :/
  }
}

I mean, how does it all work? Is a linked list something like a stack?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2016-02-29
@zagayevskiy

The answer to all your questions is pointers . Answering within the framework of a toaster the question of what pointers are is a thankless task, IMHO.

O
Onito, 2016-02-29
@Onito

brief description:
1) first stores a pointer but the top of the list (first = newlink;) here we create a new element and store a pointer to it.
2) newlink->next = first; - the previous top of the list is stored here
3) link* current = first; here we take the top of the list and just copy it to another variable
4) current = current->next; - from paragraph 2) it is clear that a pointer to the previous vertex is stored here, in other words, to the previous element.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question