Created
November 29, 2015 12:34
-
-
Save jitsceait/536d13d32466d7605e7a to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
typedef struct Node { | |
int data; | |
struct Node * next; | |
} Node; | |
Node * createNode(int val){ | |
Node * temp = (Node *)malloc(sizeof(Node)); | |
if(temp){ | |
temp->data = val; | |
temp->next = NULL; | |
} | |
return temp; | |
} | |
/* This function inserts node at the head of linked list */ | |
void push(Node **headRef, int data){ | |
Node * newNode = createNode(data); | |
newNode->next = *headRef; | |
*headRef = newNode; | |
} | |
void printList(Node *head){ | |
while(head){ | |
printf("%d->", head->data); | |
head = head->next; | |
} | |
printf("Null"); | |
} | |
/* Function to find middle node using hare and tortoise algo */ | |
Node * findMiddleNode_1(Node * head){ | |
//Wrong list, there is no middle node. | |
if(!head) return NULL; | |
Node *fast = head->next; | |
Node *slow = head; | |
while(fast){ | |
fast = fast->next; | |
//check if fast is not null yet | |
if(fast) | |
fast = fast->next; | |
slow = slow->next; | |
} | |
return slow; | |
} | |
int main(void) { | |
Node * head = NULL; | |
push(&head, 3); | |
push(&head, 4); | |
Node * nodeToDelete = head; | |
push(&head, 5); | |
push(&head, 6); | |
push(&head, 7); | |
push(&head, 8); | |
push(&head, 9); | |
printf("\nOriginal list :"); | |
printList(head); | |
Node *mid = findMiddleNode_1(head); | |
printf("\nMiddle node : %d", mid ? mid->data : 0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment