recent

Write a C Program/Function to print the middle of a given linked list(Method 2)

C Program/Function to print the middle of a given linked list:-

->Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When  the fast pointer reaches at the end of Linked List, slow pointer will reach middle of the linked list

#include<stdio.h>
#include<stdlib.h>

struct node{

int data;
struct node *next;
};

void insert(struct node **head,int new_data)
{
struct node *new_node;
new_node=(struct node*)malloc(sizeof(struct node));

new_node->data=new_data;
new_node->next=*head;
*head=new_node;

}

void TraverseTillMiddle(struct node *head)
{
struct node *p,*q;
p=head;
q=head;
while(q->next!=0 && q->next->next!=0)
{
p=p->next;
q=q->next->next;
}
printf("%d\n",p->data);
}

main()
{

struct node *head;
head=(struct node*)malloc(sizeof(struct node));

insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);
insert(&head,5);
insert(&head,6);
insert(&head,7);

TraverseTillMiddle(head);

}
Powered by Blogger.