Created
April 26, 2017 10:19
-
-
Save thinkphp/e88e994fefb59cb027bddea51730c18f to your computer and use it in GitHub Desktop.
Given a singly linked list, find if the linked list is circular or not. A linked list is called circular if it not NULL terminated and all nodes are connected in the form of a cycle. An empty linked list is considered as circular.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
typedef struct node { | |
int data; | |
struct node* next; | |
} Node; | |
void push(Node** head, Node** tail, int data) { | |
Node* new_node = (Node*)malloc(sizeof(Node)); | |
new_node->data = data; | |
new_node->next = NULL; | |
if((*head) == NULL) { | |
(*head) = new_node; | |
} else { | |
(*tail)->next = new_node; | |
} | |
(*tail) = new_node; | |
}; | |
void print(Node*head) { | |
while(head){ | |
printf("%d ", head->data); | |
head = head->next; | |
} | |
}; | |
int isCircular(Node*head) { | |
Node *curr = head; | |
while(curr != NULL) { | |
curr = curr->next; | |
if(curr == head) { | |
return 1; | |
break; | |
} | |
} | |
return 0; | |
}; | |
int main() { | |
Node *head = NULL, | |
*tail = NULL; | |
push(&head,&tail,1); | |
push(&head,&tail,2); | |
push(&head,&tail,3); | |
push(&head,&tail,4); | |
push(&head,&tail,5); | |
push(&head,&tail,6); | |
push(&head,&tail,7); | |
tail->next = head; | |
printf("%d\n", isCircular(head)); | |
return(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment