Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <stdio.

h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

int indexOf(Node *p[], Node *find, int length) {


for(int i = 0; i < length; i++) {
if(p[i] == find) {
return i;
}
}
return -1;
}
int isLoop(Node *head) {
Node *visited[100];
if(head == NULL)
return 0;
Node *temp = head;
int index = 0;
while(temp!=NULL) {
if(indexOf(visited, temp, index) != -1) {
return 1;
}
visited[index] = temp;
temp = temp->next;
index++;
}
return 0;
}
int isLoopOptimized(Node *head) {
Node *slow = head->next;
Node *fast = head->next;
while(slow != NULL && fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast) {
return 1;
}
}
return 0;
}
int main(void) {
Node* head = (Node*) malloc(sizeof(Node*));
head->data = 5;
head->next = (Node*) malloc(sizeof(Node*));
head->next->data = 10;

head->next->next = (Node*) malloc(sizeof(Node*));


head->next->next->data = 20;

head->next->next->next = head->next;

if(isLoop(head)) {
printf("isLoop: Yes\n");
} else {
printf("isLoop: No\n");
}

if(isLoopOptimized(head)) {
printf("isLoopOptimized: Yes\n");
} else {
printf("isLoopOptimized: No\n");
}
return 0;
}

You might also like