Friday, June 18, 2021
Home coding Write a program to find middle of linkedlist

Write a program to find middle of linkedlist

Given a linkedlist ,we have to make a program to find the middle node of linkedlist .

Example:

Input:1 2 3 4 5 
Output:3

Logic:

STEP 1:Start traversing a linkedlist till we reach end of linkedlist.
STEP 2:find the length of linkedlist first.
STEP 3:then again traverse till half of length of linkedlist.

Code

int MiddleLinkedlist(Node *head,int k)
{
    if(head==NULL)
    {
        return;
    }
    int count=0;
    Node *temp=head;
    while(head!=NULL)
    {
        count++;
        head=head->next;
       
    }
    int mid=count/2;
    int k=0;
while(temp!=NULL && k<mid)
{
    
    temp=temp->next;
    k++;
}
return temp->data;
}

Ouput:

1 2 3 4 5 6 7
4

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments