Given a singly linked list, find if there exist a loop.
Given a singly linked list, find if there exist a loop.
Solution:
#include "stdafx.h"
#include <iostream>
using namespace std;
class Node
{
public:
void addNode(Node* node);
void loopStart();
void loopEnd();
void setVal(int val) {this->val = val;}
int getVal() {return this->val;}
Node(int val) {this->val = val;}
bool isLoopExist();
void setN();
Node* start_end_node;
int val;
Node* next;
Node* end;
int n;
};
void Node::addNode(Node* node)
{
if(end == NULL)
*end = Node(0);
else
{
end->next = node;
end = end->next;
}
}
void Node::loopStart()
{
start_end_node = end;
}
void Node::loopEnd()
{
end->next = start_end_node;
}
bool Node::isLoopExist()
{
if(this && this->next)
{
Node* first = this;
Node* second = this;
while(first != second)
{
first = first->next;
second = second->next->next;
}
return true;
}
return false;
}
int _tmain(int argc, _TCHAR* argv[])
{
Node* head = new Node(0);
head->end = head;
Node* head_next = head;
int i = 0;
for(i=1; i<10; ++i)
{
Node* temp = new Node(i);
head->addNode(temp);
}
head->loopStart();
int j = 0;
for(j=10; j<20; ++j)
{
Node* temp = new Node(j); //if we define objects here, then the stack gonna automatic delete itself
// 以后遇到链表问题不用多想,一律用指针
head->addNode(temp);
}
head->loopEnd();
if(head->isLoopExist())
{
cout << "a loop exist" << endl;
}
else
{
cout << "no loop exist" << endl;
}
return 0;
}
浙公网安备 33010602011771号