I would like to insert the data in a sorted manner in a sorted linked list. I am able to insert the data but it is not sorted. Can anyone help me as to what i am doing wrong? Here is my function:
typename SortedList<T>::iterator SortedList<T>::insert(const T& data) {
if (data < front_->data_) {
Node* n = new Node(data, front_, nullptr);
//if empty
if (front_ == nullptr) {
//make back pt to node
back_ = n;
}
else {
//make front's previous point to node
front_->prev_ = n;
}
//make front point at node
front_ = n;
return SortedList<T>::iterator(n);
}
else {
Node* nn = new Node(data, nullptr, back_);
//if empty
if (front_ == nullptr) {
//make front_ pt to node
front_ = nn;
}
else {
//make back's next point to node
back_->next_ = nn;
}
//make back point at node
back_ = nn;
return SortedList<T>::iterator(nn);
}
And here is my class
class SortedList{
struct Node {
T data_;
Node* next_;
Node* prev_;
Node(const T& data = T{}, Node* nx = nullptr, Node* pr = nullptr) {
data_ = data;
next_ = nx;
prev_ = pr;
}
};
Node* front_;
Node* back_;
int sizelist;
}