Hi everybody. I'm trying to reverse Linked List but I face some difficulties. I'm using two lists. The first one is the one that I want to reverse. The second list is for help. It's something like stack. When I print the result of the second list, it outputs the reversed elements of the first list but then it also inputs the first list again. I think something is wrong with my loop but.. :/
Here are the two functions that I use:
1 2 3 4 5 6 7 8 9
template<class T>
void List<T>::Insert_After(List *temp1, T x)
{
List *temp2 = new List;
*temp2 = *temp1;
temp2->data = x;
temp2->next = temp1->next;
temp1->next = temp2;
}
The design of your list is very bad. Why does each node have the data member List *start_ptr;?
It is much better to decclare internal structure Node inside your class List with one constructor. For example
1 2 3 4 5 6
struct Node
{
Node *next;
T data;
Node( const T &data, Node *next = nullptr ) : data( data ), next( next ) {}
} *Head;
The design of your list is very bad. Why does each node have the data member List *start_ptr;?
It is much better to decclare internal structure Node inside your class List with one constructor. For example
I tried to do whay you said but I get an error when I declare new variables in the other functions. For example on the 33 roll in my code I get this:
missing template arguments before '*' token
This is my structure:
1 2 3 4 5 6
template<class T>
struct Node
{
T data;
Node *next;
};
The start_pointer is still in the List definition. Should I move it too?
@ vlad: The node constructor should not take T by reference.
@ Snaksa: I agree with vlad though, in context:
1 2 3 4 5 6 7 8 9 10 11 12
class List
{
private:
Node
{
Node* next;
T data;
Node ( /* ... */ )
} * head;
public:
/* ... */
};
The output you printed means that something is very wrong with your methods. You succesfully reversed the list, but the old head's next is not null. This wouldn't be so bad, but the fact that the output isnt an infinate loop means that the D in the beginning of the list is not the D at the end of the list.
Forget list1 and list2:
1 2 3 4 5 6 7 8 9 10
class List
{
/* ... */
};
int main()
{
List myList;
/* ... */
}