Adding an item to the end of a doubly linked list

Hello, I didn't fully understand how to add items to a doubly linked list. Here I added to the top of the list. How do I add to the end of the list?

    void plus (float av_point, int num, string surn){
    Students *tmp=new Students;
    tmp->Next=NULL;
    tmp->average_point=av_point;
    tmp->number=num;
    tmp->surname=surn;
    if (head!=NULL){
        tmp->Prev=tail;
        tail->Next=tmp;
        tail=tmp;
    }
    else{
        tmp->Prev=NULL;
        head=tail=tmp;
    }
}

How do I add to the end of the list? There is a structure of this type.

struct Students{
string surname;
int number;
float average_point;
string study; 
Students *Next, *Prev;
Author: HiHello, 2017-04-23

2 answers

When you add a new item to the end of a linked list, you need to:
1. The old end of the list is next to the new end of the list (and the new end of the list is the previous one).
2.The new end of the list did not have the previous element.
3. Updated information about the new end of the list

tmp->Next = tail; //Новый хвост смотрит на старый
tmp->Prev = null; //Новый хвост ни на что не оборачивается
tail->Prev = tmp; //Старый хвост оборачивается на новый
tail = tmp; //Запоминаем указатель на новый хвост

If you want to implement a closed connected list, you need to put head in tmp->Prev , and tmp in head->Next, respectively.

 1
Author: Morlok, 2017-04-23 21:20:19

I would advise you, when studying a data structure, to first draw it and consider how it looks on paper (but this is IMHO, it's easier for me). In general, here:

n = new Node(...);
tail->next = n;
tail->next->prev = tail;
tail = n;

If head != nullptr;

 0
Author: vados inferno, 2017-08-01 07:14:48