'Forward_List Split function, confused with pointer
I have just start C++ and learned about pointers and I need some hints.
The code is about splitting a forward list into two (*this and *other). I think I have gotten the finding mid point right but I am really confuse about the pointers at the end (causing errors). I think I might have pointed ptr to lists but I am not sure. Can someone please giving me some ideas.
template <typename T>
class Forward_list
{
public:
class Node
{
public:
// A node will hold data of type T
T data{};
// next will point to the next node in the list
// we initialise next to nullptr
Node* next = nullptr;
Node(){}
Node(T input_data, Node* next_node= nullptr)
{
data = input_data;
next = next_node;
}
// Destructor
~Node(){}
};
private:
// private member variables for Forward_list
unsigned size_ = 0;
Node* head_ = nullptr;
template <typename T>
Forward_list<T> Forward_list<T>::split() {
Node* other = nullptr;
Node* tmp = this->head_;
struct Node* current = this->head_;
int length = this->size();
int mid = (length-1) / 2;
for(int i = 0; i < mid; i++) {
tmp = tmp->next;
}
*other = current->next;
current->next = nullptr;
return *this;
}
Not sure if this is enough to be understood. Thanks for the help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
