samedi 29 juin 2019

How to insert values into single linked list

I'm trying to learn some basics about single linked lists, so I went with idea of creating some code. Sadly, I have given constructor to follow.

Untill now I've created all methods I've wanted. Unfortunately, seems like my insert doesn't work, so I can't even check if other methods works. Ofc role of insert method is to add number into sorted list L. This number should be put before first number, if it's bigger or put at the end of the list, if there is no such number.

#include <iostream>
#include <cassert>
using namespace std;

struct lnode
{
    int key;
    lnode* next;
    lnode(int k, lnode* n=nullptr):key(k),next(n){}
};

void insert( lnode* &L, int x)
{
    while(L)
    {
        if(x >= L->key)
        {
            L = L->next;
        }
        else
        {
            lnode* temp = L;
            L = new lnode(x, nullptr);
            L->next = temp;
            break;
        }
    }


}

int main()
{
    lnode* t = nullptr;

    insert(t,3);
    insert(t,4);
    insert(t,1);
    insert(t,7);
    insert(t,-4);
    insert(t,9);
    insert(t,2);

        while(L) {
        std::cout << L->key << " ";
    }
}

What do I expect? My expectations is to see elements of my list. At this moment there is nothing. No error, no result.

Aucun commentaire:

Enregistrer un commentaire