Jednosměrný seznam s ukazateli na první a poslední prvek

#include <iostream>
using namespace std;
 
struct Item;
 
struct List
{
    Item * first;
    Item * last;
};
 
struct Item
{
    string name;
    int    r, g, b;
    Item * next;
};
 
void init (List & a) // prazdny seznam
{
    a.first = nullptr;
    a.last = nullptr;
}
 
void insertFirst (List & a, string name0, int r0, int g0, int b0)
{
    Item* t = new Item;
 
    t->name = name0;
    t->r = r0;
    t->g = g0;
    t->b = b0;
 
    t->next = a.first; // za novym prvkem bude dosud prvni prvek
 
    a.first = t; // prvni bude novy prvek
 
    if (a.last == nullptr)
        a.last = t; // pokud je seznam prazdny tak i posledni bude novy prvek
}
 
void insertLast (List & a, string name0, int r0, int g0, int b0)
{
    Item* t = new Item;
 
    t->name = name0;
    t->r = r0;
    t->g = g0;
    t->b = b0;
 
    t->next = nullptr; // nikdo za novym prvkem nebude
 
    if (a.last != nullptr) // pokud seznam neni prazdny
        a.last->next = t; // pripojime novy prvek za posledni prvek
 
    a.last = t; // posledni bude novy prvek
 
    if (a.first == nullptr) // pokud byl seznam prazdny
        a.first = t; // prvni bude take novy prvek
}
 
void print (List & a)
{
    Item* t = a.first;
    while (t != nullptr)
    {
        cout << t->name << " " << t->r << "," << t->g << "," << t->b << endl;
        t = t->next;
    }
}
 
int main ()
{
    List a; // promenna pro nas seznam
    init (a);
 
    insertLast (a, "cervena", 255, 0, 0);
    insertLast (a, "zelena", 0, 255, 0);
    insertLast (a, "modra", 0, 0, 255);
 
    print (a);
    return 0;
}
 
zpro/first_and_last.txt · Last modified: 2022/02/08 17:26 by 77.236.222.24
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki