How to insert a number into an arbitrary position, into a position I want?

Asked

Viewed 40 times

0

Hello, all right? I have this code and I need to know how to insert a value in an arbitrary position, I tried in a few ways, but I couldn’t. Follows the code:

#ifndef LIST_H
#define LIST_H

template<typename T>
class List {
public:
List() : head(nullptr), tail(nullptr), _size(0) {}

~List() 
{
    auto p = head;

    while (p)
    {
        auto next = p->next;
        delete p;
        p = next;
    }
}

const T& front() const
{
    if (head)
        return head->info;
    else
        throw "Empty list!";
}

const T& back() const
{
    if (tail)
        return tail->info;
    else
        throw "Empty list!";
}

bool empty() const { return head == nullptr; }

unsigned long size() const { return _size; }

void push_front(const T& info)
{
    auto n = new Node(info, head);

    tail = head ? tail : n;
    head = n;
    _size++;
}

void push_back(const T& info)
{
    auto n = new Node(info, nullptr);

    tail ? tail->next = n : head = n; 
    tail = n;
    _size++;
}

void pop_front()
{
    if (!head)
        throw "Lista vazia";

    auto temp = head;
    head = head->next;
    delete temp;

    tail = head ? tail : nullptr;
    _size--;
}

void pop_back()
{
    if (!head)
        throw "Lista vazia";

    auto prev = head;

    while (prev->next and prev->next != tail)
        prev = prev->next;

    delete tail;

    tail == head ? (head = tail = nullptr)
        : (tail = prev, tail->next = nullptr);

    _size--;
}

private:
struct Node {
    T info;
    Node *next;

    Node(const T& i, Node *n) : info(i), next(n) {}
};

Node *head, *tail;
unsigned long _size;
};

#endif
  • The question is not clear. Is the question about any of the methods that are done that do not work correctly ? Or is it about making a new method with a certain logic ?

  • About making a method with a certain logic. For example, I can’t put an element in any position, I’m doing the code, but I still can’t. This is it for now: void Insert(const T& info, int position) { if(position == 0) { push_front(info); Return; } Else if(position == _size - 1) { push_back(info); Return; } auto element = head; for(int i = 0; i < position; i++) element = element->next; auto n = new Node(info, element); }

  • If you’re doing the code and you already have something, what you have should be in the question. In fact all other methods should not be in the question as they end up confusing the reader since they are not related to doubt

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.