Print Middle element of LL
Method 1:
Traverse linked list using two pointers. Move first pointer by one and second pointer by two, when second pointer reaches to the end of the list, then first pointer will reach to the middle of the list.
Implementation in C:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
int main()
{
struct node* head = NULL;
push(&head,1);
push(&head,2);
push(&head,3);
push(&head,4);
push(&head,5);
push(&head,6);
push(&head,7);
printMiddle(head);
return 0;
}
void push(struct node** ref, int newData)
{
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = newData;
newNode->next = (*ref);
(*ref) = newNode;
}
void printMiddle(struct node* head)
{
struct node* p=head;
struct node* q=head;
while(q!= NULL && q->next!=NULL)
{
p=p->next;
q=q->next->next;
}
printf("\nMiddle element is: %d",p->data);
}
Method 2:
Traverse through the list using one pointer and initialize a counter variable with 0 and increment the pointer on every odd value of counter and at the end,pointer will move only half of the total length of the list.
Implementation in C:
Output:
Traverse linked list using two pointers. Move first pointer by one and second pointer by two, when second pointer reaches to the end of the list, then first pointer will reach to the middle of the list.
Implementation in C:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
int main()
{
struct node* head = NULL;
push(&head,1);
push(&head,2);
push(&head,3);
push(&head,4);
push(&head,5);
push(&head,6);
push(&head,7);
printMiddle(head);
return 0;
}
void push(struct node** ref, int newData)
{
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = newData;
newNode->next = (*ref);
(*ref) = newNode;
}
void printMiddle(struct node* head)
{
struct node* p=head;
struct node* q=head;
while(q!= NULL && q->next!=NULL)
{
p=p->next;
q=q->next->next;
}
printf("\nMiddle element is: %d",p->data);
}
Method 2:
Traverse through the list using one pointer and initialize a counter variable with 0 and increment the pointer on every odd value of counter and at the end,pointer will move only half of the total length of the list.
Implementation in C:
void printMiddle(struct node* head) { int count=0; struct node* p=head; while(head!= NULL) { if(count &1) { p=p->next; } count++; head=head->next; } printf("\nMiddle element is: %d",p->data); }
Output:
Middle element is: 4
Comments
Post a Comment