Write a program in C to print the middle most node of a given linked list

Find the middle of a given linked list

Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3.
If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the output should be 4.

C Program For Finding The Middle Element Of A Given Linked List

Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3.
If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the output should be 4.

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Method 1:
Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2.

Method 2:
Traverse linked list using two pointers. Move one pointer by one and the other pointers by two. When the fast pointer reaches the end slow pointer will reach the middle of the linked list.

Below image shows how printMiddle function works in the code :



C




// C program to find middle of linked list
#include
#include
// Link list node
struct Node
{
int data;
struct Node* next;
};
// Function to get the middle of
// the linked list
void printMiddle[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;
}
printf["The middle element is [%d]",
slow_ptr->data];
}
}
void push[struct Node** head_ref,
int new_data]
{
// Allocate node
struct Node* new_node =
[struct Node*] malloc[sizeof[struct Node]];
// Put in the data
new_node->data = new_data;
// Link the old list off the new node
new_node->next = [*head_ref];
// Move the head to point to the new node
[*head_ref] = new_node;
}
// A utility function to print a given
// linked list
void printList[struct Node *ptr]
{
while [ptr != NULL]
{
printf["%d->", ptr->data];
ptr = ptr->next;
}
printf["NULL"];
}
// Driver code
int main[]
{
// Start with the empty list
struct Node* head = NULL;
int i;
for [i = 5; i > 0; i--]
{
push[&head, i];
printList[head];
printMiddle[head];
}
return 0;
}

Output:

5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4] 1->2->3->4->5->NULL The middle element is [3]

Method 3:
Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list.
Thanks to Narendra Kangralkar for suggesting this method.

C




// C program to implement the
// above approach
#include
#include
// Link list node
struct node
{
int data;
struct node* next;
};
// Function to get the middle of
// the linked list
void printMiddle[struct node* head]
{
int count = 0;
struct node* mid = head;
while [head != NULL]
{
// Update mid, when 'count'
// is odd number
if [count & 1]
mid = mid->next;
++count;
head = head->next;
}
// If empty list is provided
if [mid != NULL]
printf["The middle element is [%d]",
mid->data];
}
void push[struct node** head_ref,
int new_data]
{
// Allocate node
struct node* new_node =
[struct node*]malloc[sizeof[struct node]];
// Put in the data
new_node->data = new_data;
// Link the old list off the new node
new_node->next = [*head_ref];
// Move the head to point to the new node
[*head_ref] = new_node;
}
// A utility function to print a
// given linked list
void printList[struct node* ptr]
{
while [ptr != NULL]
{
printf["%d->", ptr->data];
ptr = ptr->next;
}
printf["NULL"];
}
// Driver code
int main[]
{
// Start with the empty list
struct node* head = NULL;
int i;
for [i = 5; i > 0; i--]
{
push[&head, i];
printList[head];
printMiddle[head];
}
return 0;
}

Output:

5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4] 1->2->3->4->5->NULL The middle element is [3]

Please refer complete article on Find the middle of a given linked list for more details!




Article Tags :
C Language
C Programs
Linked List
Adobe
Amazon
Flipkart
GE
Hike
Linked Lists
MAQ Software
Microsoft
Morgan Stanley
Nagarro
Payu
Qualcomm
Samsung
Veritas
VMWare
Wipro
Zoho
Practice Tags :
VMWare
Zoho
Flipkart
Morgan Stanley
Amazon
Microsoft
Samsung
Hike
Payu
MAQ Software
Adobe
Wipro
Qualcomm
Nagarro
GE
Veritas
Linked List
Read Full Article

Find middle node of a linked list using slow and fast pointer.

Algorithm to print middle node of linked list
Let "head" be the head pointer of given linked list.
  • We will use two pointers "front" and "back" pointer. Initially, set both pointer to head node.
  • Using a loop, traverse linked list until fast pointer reached last node of linked list.[fast != NULL && fast->next != NULL]
  • In every iteration, slow pointer will move one node whereas fast pointer will move two node.
  • When fast pointer reaches last node then slow pointer will be pointing to middle node.

In this program, we will use a user defined function "printMiddleNode" which takes head node of a linked list as input and print middle node by implementing above mentioned algorithm.

void printMiddleNode[struct node *head]{ /* Input Validation */ if[head == NULL]{ printf["Error : Invalid Input !!!!\n"]; return INT_MIN; } struct node *slow, *fast; slow = fast = head; while[fast != NULL && fast->next != NULL] { fast = fast->next->next; slow = slow->next; } printf["\nMiddle Node : %d\n", slow->data]; } C program to print middle node of a linked list.#include #include /* A structure of linked list node */ struct node { int data; struct node *next; } *head; void initialize[]{ head = NULL; } /* Given a Inserts a node in front of a singly linked list. */ void insert[int num] { /* Create a new Linked List node */ struct node* newNode = [struct node*] malloc[sizeof[struct node]]; newNode->data = num; /* Next pointer of new node will point to head node of linked list */ newNode->next = head; /* make new node as new head of linked list */ head = newNode; printf["Inserted Element : %d\n", num]; } void printMiddleNode[struct node *head]{ /* Input Validation */ if[head == NULL]{ printf["Error : Invalid Input !!!!\n"]; return INT_MIN; } struct node *slow, *fast; slow = fast = head; /* In every iteration, slow pointer will move one nede whereas fast pointer will move two node. When fast pointer reaches last node then slow pointer will be pointing to middle node */ while[fast != NULL && fast->next != NULL] { fast = fast->next->next; slow = slow->next; } printf["\nMiddle Node : %d\n", slow->data]; } /* Prints a linked list from head node till tail node */ void printLinkedList[struct node *nodePtr] { while [nodePtr != NULL] { printf["%d", nodePtr->data]; nodePtr = nodePtr->next; if[nodePtr != NULL] printf["-->"]; } } int main[] { initialize[]; /* Creating a linked List*/ insert[3]; insert[7]; insert[12]; insert[5]; insert[9]; printf["\nLinked List\n"]; printLinkedList[head]; /* Printing Middle Node of Linked List */ printMiddleNode[head]; return 0; } Output
Inserted Element : 3 Inserted Element : 7 Inserted Element : 12 Inserted Element : 5 Inserted Element : 9 Linked List 9-->5-->12-->7-->3 Middle Node : 12 Method 1

C

#include
#include
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Function to get the middle of the linked list*/
void printMiddle[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;
}
printf["The middle element is [%d] ", slow_ptr->data];
}
}
void push[struct Node** head_ref,int new_data]
{
/* allocate node */
struct Node* new_node =
[struct Node*]malloc[sizeof[struct Node]];
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = [*head_ref];
/* move the head to point to the new node */
[*head_ref] = new_node;
}
// A utility function to print a given linked list
void printList[struct Node *ptr]
{
while [ptr != NULL]
{
printf["%d->", ptr->data];
ptr = ptr->next;
}
printf["NULL "];
}
/* Drier program to test above function*/
int main[]
{
/* Start with the empty list */
struct Node* head = NULL;
int i;
for [i=5; i>0; i--]
{
push[&head, i];
printList[head];
printMiddle[head];
}
return 0;
}

Algorithm

/* Function to find the middle of the linked list */ void findMiddle[node *head] { node *slow_ptr = head; node *fast_ptr = head; if [head!=NULL] { while [fast_ptr != NULL && fast_ptr->link != NULL] { fast_ptr = fast_ptr->link->link; slow_ptr = slow_ptr->link; } printf[" The middle element is %d \n", slow_ptr->data]; } }

But there is another way which is very efficient. Traverse linked list using two pointers named as fast and slow. Move slow pointer by one node and fast pointer by two node in single iteration. When the fast pointer reaches end slow pointer will reach middle of the linked list.

How our program will behave?

Our program will take one node as an input and add to linked list.

After taking the node program will give options to select options what you want to perform.

This program has 4 operations. You can select any one as per your requirement.

This 4 operation are:

  1. Add value to the list at end, it is to insert node in the list.
  2. Traverse/View list. It is for showing complete list.
  3. This 3rd option is for finding middle of a singly linked list.
  4. to exit the program.

Program to find middle element of a linked list in single pass

#include #include #include struct node{ int data; struct node *next; }; struct node *head=NULL; struct node* createNode[]{ struct node *newNode = [struct node *]malloc[sizeof[struct node]]; return [newNode]; } void insertNodeAtEnd[]{ struct node *temp,*ptr; temp=createNode[]; printf["enter the data you want to insert:"]; scanf["%d",&temp->data]; temp->next=NULL; if[head==NULL] head=temp; else{ ptr=head; while[ptr->next!=NULL]{ ptr=ptr->next; } ptr->next=temp; } } void viewList[]{ struct node* temp=head; if[temp==NULL]{ printf["List is empty. Please insert some data in list \n"]; } else{ printf["Our list is : \n"]; while[temp->next!=NULL] { printf["%d\t",temp->data]; temp=temp->next; } printf["%d \t",temp->data]; } } void findMiddle[]{ struct node* t= head; int elements=0; while[t]{ t=t->next; elements++; } int middle = elements/2; t=head; for [int i = 1; i < middle + 1; i++] t = t->next; printf["middle number of list is :\n "]; printf["%d",t->data]; } int menu[]{ int choice; printf["\n 1.Add value to the list at end"]; printf["\n 2.Travesre/View List"]; printf["\n 3.Print Middle element of a list "]; printf["\n 4.exit"]; printf["\n Please enter your choice: \t"]; scanf["%d",&choice]; return[choice]; } void main[]{ while[1]{ switch[menu[]]{ case 1: insertNodeAtEnd[]; break; case 2: viewList[]; break; case 3: findMiddle[]; break; case 4: exit[0]; default: printf["invalid choice"]; } getch[]; } }

Output:

Video liên quan

Bài Viết Liên Quan

Bài mới nhất

Chủ Đề