Tuesday, January 19, 2021

Middle of a Linked list

 For even number of nodes, we have to print the second node.

There are 2 approaches to do that: 1. 2 pointer app  2.head pointing to the middle app


1. 2 pointer approach

#include <iostream>

#include <bits/stdc++.h>

using namespace std;


//using 2 pointer approach

struct Node{

    int data;

    struct Node* next;

};


void printmid(struct Node* head)

{

    struct Node *slow_ptr= head;

    struct Node *fast_ptr= head;

    if(head!= NULL)

    {

         while(fast_ptr!=NULL && fast_ptr->next!=NULL)

         {

             fast_ptr= fast_ptr->next->next;

             slow_ptr=slow_ptr->next;

         } //while ends

         printf("the middle element is[%d]\n\n", slow_ptr->data);

    } //if ends

    

    

} //funtion ends


void push(struct Node** head_ref, int new_data)

{

    struct Node* new_node= new Node;

    new_node->data= new_data;

    new_node->next= (*head_ref);

    (*head_ref)= new_node;


//funtion to print given linked list

void printlist(struct Node* ptr)

{

    while(ptr!= NULL)

    {

        printf("%d->", ptr->data);

        ptr= ptr->next;

    } //whileends

    printf("NULL\n");

} //function ends



int main() {

struct Node* head= NULL; //take an empty linkedlist

    for(int i=5; i>0; i--)

    {

        push(&head, i);

        printlist(head);

        printmid(head);

    }

return 0;

}

2. MID-> HEAD pointer approach


#include <iostream>

#include <bits/stdc++.h>

using namespace std;


//using head mid app

struct node{

    int data;

    struct node* next;


};



//function to get the mid elelment

void printmid(struct node* head)

{

    int count=0;

    struct node* mid= head;

    while(head!=NULL)

    {

        if (count & 1) mid= mid->next; ++ count; head=head->next;

        

    } //loop ends

    

    if(mid!=NULL) printf("mid element is[%d]\n\n", mid->data);

    

} //f ends


void push(struct node** head_ref, int new_data)

{

   struct node* new_node= new node() ;

   new_node->data= new_data;

   new_node-> next= (*head_ref);

   (*head_ref)= new_node;

    

} //f ends


//f to print linked list given

void printlist(struct node* ptr)

{

    while(ptr!=NULL) {printf("%d->", ptr->data); ptr=ptr->next;} //whileends

    printf("NULL\n");

} //f ends


int main() {

struct node* head= NULL;

int i;

for(i=5; i>0; i--) {push(&head, i); printlist(head); printmid(head);}

return 0;

}


1 Comments:

At July 30, 2021 at 8:02 AM , Blogger sid seo said...

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work linkedin ads tips

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home