Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- typedef struct Node{
- struct Node *next;
- int data;
- }Node;
- int cyclicOrNot(Node *head){
- Node *fastPtr=head;
- Node *slowPtr=head;
- if (!fastPtr)
- return 0;
- int i;
- for(i=0;;i++){
- fastPtr=fastPtr->next;
- if (i%2)
- slowPtr=slowPtr->next;
- if (!fastPtr)
- return 0;
- if (fastPtr==slowPtr)
- return 1;
- }
- }
- Node *createList(int elements, int cyclic){
- if (elements<1)
- return NULL;
- Node *head=(Node *)malloc(sizeof(Node *));
- head->data=0;
- Node *cur=head;
- int i;
- for (i=1;i<elements;i++){
- cur->next=(Node *)malloc(sizeof(Node *));
- cur=cur->next;
- cur->data=i;
- }
- if (cyclic){ //cyclic case
- int elem;
- if (cyclic<=elements)
- elem=0;
- else
- elem=cyclic;
- //find the element and make your last node point back to it
- Node *backElem=head;
- for(i=0;i<elem;i++)
- backElem=backElem->next;
- cur->next=backElem;
- }
- else //acyclic case
- cur->next=NULL;
- return head;
- }
- void printList(Node *head){
- Node *cur=head;
- //to prevent infinite loop
- int count=0;
- printf("List:");
- while (cur){
- printf("%d,",cur->data);
- cur=cur->next;
- count++;
- if(count>10){ printf("\n"); return;}
- }
- printf("\n");
- }
- int main(){
- //create an acyclic list and test it
- Node *head=createList(5,0);
- printList(head);
- if (cyclicOrNot(head))
- printf("Error: the function didn't correctly identify an acyclic list\n");
- else
- printf("Success: the function correctly identified an acyclic list\n");
- //create a cyclic list and test it
- head=createList(5,1);
- printList(head);
- if (cyclicOrNot(head))
- printf("Success: the function correctly identified a cyclic list\n");
- else
- printf("Error: the function didn't correctly identify a cyclic list\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement