Print the Middle of a given linked list

This problem is similar to the finding the middle element of linked list. we can easily solve this problem using two pointers. Let see an example.

Print middle node of linked list

In case linked list are contain even number of linked list nodes in this case there will be two possibilities of middle element. See this example.

1->2->3->4->5->6->7->8->NULL

In this situation [4,5] both are middle node. Here given code implementation process.

//C Program to print middle node of given linked list
#include<stdio.h>
#include <stdlib.h> //for malloc function

//create structure
struct Node{
  int data;
  struct Node*next;
};
//function prototype
void insert(struct Node**,int);
void display(struct Node*);
//insert Node element
void insert(struct Node**head,int value){
  //Create dynamic node
  struct Node*node=(struct Node*)malloc(sizeof(struct Node));
  if(node==NULL){
    printf("Memory overflow\n");
  }else{
    node->data=value;
    node->next=*head;
    *head=node;
  }
}
//print middle node
void print_mid(struct Node*head){
  if(head==NULL){
    printf("\nEmpty Linked list");
  }else if(head->next==NULL && head->next->next==NULL){
    printf("\nLess than 3 nodes");
  }else{
    struct Node*temp=head,*mid_element=head;
    while(temp!=NULL &&temp->next!=NULL && temp->next->next){
      mid_element=mid_element->next;
      temp=temp->next->next;
    }
    printf("\nMiddle Element : %d\n",mid_element->data);
  }

}
//Display element of Node
void display(struct Node*temp){
  
  if(temp==NULL){
    printf("Empty linked list");
  }else{
    printf("\nLinked List Node :");
    while(temp!=NULL){
      printf("%d  ",temp->data);
      temp=temp->next;
    }
  }

}
int main(){
  //create node pointer
  struct Node*head=NULL;
  //insert element of linked list
  insert(&head,7);
  insert(&head,6);
  insert(&head,5);
  insert(&head,4);
  insert(&head,3);
  insert(&head,2);
  insert(&head,1);
  //display all node
  display(head);
  print_mid(head);

  return 0;
}

Output

Linked List Node :1  2  3  4  5  6  7  
Middle Element : 4
//C++ Program to print middle node of linked list 

#include<iostream>
using namespace std;

//create structure
struct Node{
  int data;
  struct Node*next;
};
class LinkedList{
  Node *head;
public:
  LinkedList();
  void insert(int);
  void display();
  void print_mid();
};
LinkedList::LinkedList(){
  head=NULL;
  
}

//Insert Node at beginning of list 
void LinkedList:: insert(int value){
  //Create dynamic node
  struct Node*node=new Node;
  if(node==NULL){
    cout<<"Memory overflow"<<endl;
  }else{
    node->data=value;
    node->next=head;
    head=node;
  }
}
//Display element of Node
void LinkedList:: display(){
  
  if(head==NULL){
    cout<<"Empty linked list";
  }
  else{
    cout<<"\nLinked List element :";
    struct Node*temp=head;
    while(temp!=NULL){
      cout<<"  "<<temp->data;
      temp=temp->next;
    }

  }
}
//Print middle nodes
void LinkedList::print_mid(){
  if(head==NULL){
    cout<<"Empty Linked List"<<endl;
  }else if(head->next==NULL || head->next->next==NULL){
    cout<<"Less than 2 nodes of this Linked List"<<endl;
  }else{
    Node *temp=head,*middle=head;
    while(temp!=NULL&&temp->next&&temp->next->next){
      middle=middle->next;
      temp=temp->next->next;
    }
    cout<<"\nMiddle Element : "<<middle->data<<endl;
  }

}
int main(){
  LinkedList obj=LinkedList();
  //insert element in linked list
  obj.insert(7);
  obj.insert(6);
  obj.insert(5);
  obj.insert(4);
  obj.insert(3);
  obj.insert(2);
  obj.insert(1);
  //display all node
  obj.display();
  obj.print_mid();
  return 0;
}

Output

Linked List element :  1  2  3  4  5  6  7
Middle Element : 4
//Java program to print middle of linked list
class Node {
  public int data;
  public Node next;
  public Node(int value) {
    data = value;
    next = null;
  }
}

public class LinkedList {

  public Node head;
  public LinkedList() {
    head = null;
  }
  //add insert node at beginning of linked list
  public void insert(int value) {
    Node newNode = new Node(value);
    newNode.next = head;
    head = newNode;
  }
  //print middle node of linked list
  public void printMid() {
    if (head == null) {
      //when linked list are no elements
      System.out.println("Empty Linked List");
    } else if (head.next == null && head.next.next == null) {
      //when linked list are less than  of 3 nodes
      System.out.println("Less then 3 node of linked list");
    } else {
      Node temp = head, midNode = head;
      while (temp != null && temp.next != null && temp.next.next != null) {

        midNode = midNode.next;
        temp = temp.next.next;
      }

      System.out.println("\nMiddle node : " + midNode.data);

    }
  }
  public void display() {
    if (head != null) {
      System.out.print("Linked List Elements :");

      Node temp = head;
      while (temp != null) {
        System.out.print(" " + temp.data);
        temp = temp.next;
      }
    } else {
      System.out.println("Empty Linked List");
    }
  }
  public static void main(String arg[]) {
    LinkedList info = new LinkedList();
    //insert element of linked list
    info.insert(7);
    info.insert(6);
    info.insert(5);
    info.insert(4);
    info.insert(3);
    info.insert(2);
    info.insert(1);

    info.display();
    info.printMid();

  }
}

Output

Linked List Elements : 1 2 3 4 5 6 7
Middle node : 7
#Python print middle node of linked list 

class Node:
  def __init__(self,data):
    self.data=data
    self.next=None

#create class element    
class LinkedList:
  def __init__(self):
    #Assign default value
    self.head=None

  #insert new node to linked list  
  def insert(self,data):
    node=Node(data)
    node.next=self.head
    self.head=node 


  #display all linked list node 
  def display(self):
    temp=self.head
    while(temp!=None):
      print(temp.data,end=" ")
      temp=temp.next
    
  #print middle node
  def printMiddle(self):
    if(self.head==None):
      print("Empty element list\n")
    elif(self.head.next==None or self.head.next.next==None):
      print("Less then 3 node of element list") 
    else:
      temp=self.head
      middle=self.head
      while(temp!=None and temp.next!=None and temp.next.next):
        temp=temp.next.next
        middle=middle.next

      print("\nMiddle Node : ",middle.data)  

def main():
  #Create Object of class element
  element=LinkedList()

  #element list insertion
  element.insert(7)
  element.insert(6)
  element.insert(5)
  element.insert(4)
  element.insert(3)
  element.insert(2)
  element.insert(1)
  element.display()
  element.printMiddle()


if __name__=="__main__":
  main()    

Output

1 2 3 4 5 6 7 
Middle Node :  4
//C# print middle node of linked list
using System;
public class Node{
  public  int data;
  public  Node next;
}
class Program
{
  Node head;
  public Program(){
    head=null;

  }
  //insert node at beginning
  public void insert(int data){
    //make a new node
    Node element=new Node();
    element.data=data;
    element.next=head;
    head=element;

  }
  //Find and print middle node of linked list
  public void printMid(){
    if(head==null){

    }else if(head.next==null && head.next.next==null){

    }else{
      Node temp=head,midElement=head;
      while(temp!=null && temp.next!=null &&temp.next.next!=null){
        midElement=midElement.next;
        temp=temp.next.next;
      }
      Console.WriteLine("\nMiddle Node : {0}",midElement.data);
    }
  }
  //display node elements
  public void display(){
    if(head==null){
      Console.Write("Empty List");
    }else{
      Console.Write("\nNode Elements :");
      Node temp=head;
      while(temp!=null){
        Console.Write("  {0}",temp.data);
        temp=temp.next;
        if(temp==head) break;
      }

    }
  }
  static void Main()
  {
    Program obj=new Program();
    //add linked list items
    obj.insert(7);
    obj.insert(6);  
    obj.insert(5);
    obj.insert(4);
    obj.insert(3);  
    obj.insert(2);
    obj.insert(1); 

    obj.display();
    obj.printMid(); //print mid node

  }
}

Output

Node Elements :  1  2  3  4  5  6  7
Middle Node : 4
<?php
//Php program 
//print middle node of linked list 
class Node
{
    public $data;
    public $next;
    function __construct($data)
    {
        $this->data = $data;
        $this->next = NULL;
    }
}
class LinkedList{

    private $head;
    function __construct()
    {
        $head=NULL;
    }
       /*
    * Append the Given data value at end of linked list
    * Fun : insert
    * Parm: data value
    *@return None
    */
    function insert($data)
    {
        $newNode=new Node($data); 
        if($this->head==NULL)
        {
            $this->head=$newNode;
        }else{
            $temp=$this->head;
            //find last node of linked list
            while($temp->next!=NULL){
                $temp=$temp->next;
            }
            //add new node to last of linked list
            $temp->next=$newNode;
        }
    }
     //Remove middle nodes
    function print_mid(){
      if($this->head==NULL){
        echo "<br>Empty Linked List";
      }else if($this->head->next==NULL ||$this->head->next->next==NULL){
        echo "<br>Less than 2 nodes of this Linked List";
      }else{
        $temp=$this->head;
        $middle=NULL;
        //find middle node
        while($temp!=NULL&&$temp->next&&$temp->next->next){
         
           $middle=$middle->next;
   
          $temp=$temp->next->next;
        }
        echo "<br> Middle Node : ".$middle->data;
      }

    }
    //Display all inserted node in linked list
    function display()
    {
        if($this->head==NULL)
        {
            echo "Empty Linked List";
        }
        else{
            $temp=$this->head;
            echo "<br>Linked List :";
            while($temp!=NULL){
                //display node value
                echo "&nbsp;&nbsp;".$temp->data;
                $temp=$temp->next; //visit to next node
            }
        }   
    }
}
function main(){
  //Make a object of LinkedList class
  $obj= new LinkedList();
  /*
  *Insert following nodes in linked list
  */
  $obj->insert(1);
  $obj->insert(2);
  $obj->insert(3);
  $obj->insert(4);
  $obj->insert(5);
  $obj->insert(6);
  $obj->insert(7);


  //Display all node
  $obj->display();
  $obj->print_mid();
  
}
main();
?>

Output

Linked List :  1  2  3  4  5  6  7
Middle Node : 4


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved