I am trying to write a code to find the beginning of a loop in a linked list. Here is my code:
#include <iostream>
template <class T>
class LinkedList
{
public:
struct node
{
T data;
node* next;
};
node* head;
LinkedList() : head(NULL){};
void AppendToTail(T data);
void InsertToHead(T data);
void RemoveDuplicates();
void PrintList();
T lastNthNode(int N);
bool operator==(const LinkedList<T>& L);
node* FindBeginningNodeLoop();
};
template <class T>
node* LinkedList<T>::FindBeginningNodeLoop()
{
if (head == NULL)
return NULL;
node* slow = head;
node* fast = head;
while (fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
break;
}
if (fast == NULL)
return NULL;
slow = head;
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
The compiler gives the following errors:
1> main.cpp 1>c:\users...\linkedlist.h(177): error C2143: syntax error : missing ';' before '*' 1>c:\users...\linkedlist.h(177): error C2065: 'T' : undeclared identifier 1>c:\users...\linkedlist.h(177): error C2923: 'LinkedList' : 'T' is not a valid template type argument for parameter 'T' 1>c:\users...\linkedlist.h(200): error C2509: 'FindBeginningNodeLoop' : member function not declared in 'LinkedList' 1> c:\users...\linkedlist.h(5) : see declaration of 'LinkedList'
I cannot find the problem. Any help is greatly appreciated. Thanks.