Lists are linear, so it has O(n) time worst case of accessing an element.
1 2 3 4 5 6 7 8
node * current=head;
for(auto i=1; i<=n-1;++i) //lists aren't arrays so you can start from 1
{
if(current==nullptr) break; //if there are less than n-1 elements, but that shouldn't happen, you can also use assert
current=current->next;
}
But if you got a doubly linked list it's way easier on time, since you already know that you need to access the penultimate element.
Thanks for your reply but I think I did some mistake in my question.
The list that I work on it is dynamic size not fix size. I know that .back() return the last element in list but how shift the element at position -1 from back?
Regards
Well, you give each node another variable that it will be previous if you want a doubly linked list. Otherwise, just use a variable to keep track of the size of the list like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void add_element(element)
{
//do usual stuff to add an element
++size_counter;
}
void erase_element(element)
{
//do usual stuff to erase an element
--size_counter;
}
row is constant
The values of Q and A are updated periodically.
if the t=5 sec, I need to calculate the value of Q at this time depending on the value of Q at t= 4sec and A value at t= 4 sec.
How I program it?. I am thinking to use the list to store the value of Q for previous period but I always get the same values for Q(at t) and Q(at t-1)?
I wouldn't use a list for this, I'd rather use a dynamic array (i.e std::vector). So then you can simply use subscript operator ([]) to access your element.
Well, std::vector, it's basically an array that grows in size as needed (but it has far more functionality). I don't know from where you input the Qs, but the core idea is to act like this:
1 2 3 4 5 6 7
std::vector<int> values;
//introduce first element
//loop according to your needs
int N = (1-row) * values[values.size()-1]+ row * A[t-1];// values.size()-1 is the current end since it starts from 0
values.push_back(N); // pushes the element on the vector, also size increases by 1