'Split linked list into half in c++

What is wrong with my code in splitting the linked list into half, what causes the error? I kinda get the logic on how to split it, but is this the right implementation?

template <typename T>
Forward_list<T> Forward_list<T>::split()
{
    Forward_list<T> my_list;
    Node* tmp = head_;
    Node* tmp2 = head_;

if (my_list.empty() == true)
{
    return *this;
}

while (tmp != nullptr)
{
    tmp = tmp->next;
    if (tmp == nullptr) break;
    tmp = tmp->next;
    tmp2 = tmp2->next;
}
    my_list.head_ = tmp2->next;
    tmp2->next = nullptr;
    my_list.size_++;
    return my_list;
    }


Solution 1:[1]

You did not show your code. That is a pity. So, I needed to stub it.

You have 3 main errors.

  • Checking for the empty list is wrong. You are checking the just newly create my_list. This will of course always be empty.
  • The traversing of the list is wrong
  • The size calculation is wrong.

Please see the corrected code below:

template <typename T>
struct Forward_list {
    struct Node {
        T data{};
        Node* next{};
    };
    Node* head_{};
    unsigned int size_{};

    Forward_list<T> split();

    void push_back(const T& t);
    bool empty() const { return size_ == 0; }
};

template <typename T>
void Forward_list<T>::push_back(const T& t) {

    Node* data = new Node{ t,nullptr };

    if (head_ == nullptr)
        head_ = data;
    else {

        Node* tmp{ head_ };
        while (tmp->next)
            tmp = tmp->next;
        tmp->next = data;
    }
    ++size_;

}

template <typename T>
Forward_list<T> Forward_list<T>::split()
{
    Forward_list<T> my_list;
    Node* tmp = head_;
    Node* tmp2 = head_;

    if (/*my_list.*/empty() == true)
    {
        return *this;
    }

    while (tmp->next != nullptr)
    {
        tmp = tmp->next;
        if (tmp->next == nullptr) break;
        tmp = tmp->next;
        tmp2 = tmp2->next;
    }
    my_list.head_ = tmp2->next;
    tmp2->next = nullptr;
    my_list.size_ = size_/2; 
    size_ = size_ - my_list.size_;
    return my_list;
}
int main() {
    Forward_list<int> fw;
    for (int i{}; i < 3; ++i)
        fw.push_back(i);

    Forward_list<int> fw2 = fw.split(); 

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Armin Montigny