DS – Slow Fast Pointer in C

Slow and Fast Pointers in Single Linked List:

  • Slow pointer and fast pointer are simply the names given to two pointer variables.
  • The only difference is that, slow pointer travels the linked list one node at a time where as a fast pointer travels the linked list two nodes at a time.
#include<stdio.h>
#include<stdlib.h>
 
struct Node
{
            int data;
            struct Node* link;
};
struct Node* root=NULL;
 
int length();
struct Node* create(int);
struct Node* insert(struct Node*,int);
int middle();
void display();
 
int main()
{
            int i,x;
            for(i=10 ; i<=100 ; i+=10)
            {
                        root = insert(root, i);
            }
            x = middle();
            printf(“Middle value : %d\n”,x);
            return 0;
}
 
struct Node* create(int ele)
{
            struct Node* temp;
            temp=(struct Node*)malloc(sizeof(struct Node));
            temp->data=ele;
            temp->link=NULL;
            return temp;
}
 
struct Node* insert(struct Node* temp, int ele)
{
            if(temp==NULL)
            {
                        return create(ele);
            }
            else
            {
                        temp->link = insert(temp->link,ele);
            }
            return temp;
}
 
int middle()
{
            struct Node *fast, *slow;
            slow=fast=root;
            while(fast->link!=NULL && fast->link->link!=NULL)
            {
                        slow=slow->link;
                        fast=fast->link->link;
            }
            return slow->data;
}
Scroll to Top