How to Return Middle of Linked List in C Programming?

3 Min Read

How to return the middle of linked list in c?

How to return the middle of linked list in c? A linked list containsmany nodes. when you want to find the middle node of a given linked list you can use the traversing algorithm.

Traversing through the linked List

Traversing algorithm use to find the specific node in linked list. It visits each node in a linked list from the root node leaf node. Traversing algorithm used to perform the arithmetic operations, finding the largest and smallest node, finding the position of a specific node by value and so.It involves in the following step.

The traversing algorithm starts with the first node. It checks the node position and node value. It fetches the value of the node.

It performs the condition check till the last node of the leaf and produces the output.

Consider if the linked list is 1->2->3->4->5. You need to return the middle of this linked list. You can use the following methods.

Method 1:

The traverse algorithm performs based on the condition count/2 condition.

The traversing algorithm starts with the first node. It checks for the conditions count/2. It fetches the position and values of each node.

It initializes the count values as 0. The count value will be increased one by one. When it reaches the last node and the next node is NULL, it performs the count/2 conditions.

If the count value is odd, then it performs the round-off operation to produce the middle node. If the count value is even then it returns 0 as an output.

Method 2:

In the method, tow traversing can be performed by two pointers. One pointer performs the traverse one by one. Another pointer performs the traverse by two by two.

Consider the two parameters ptr1 and ptr2. Your linked list is 1->2->3->4->5. Both the ptr1 and ptr2 starts the traversing from the first node.

When ptr1 is on second node(node value=2), the ptr2 will move to third node(nodevalue=3).

Similarly, when the ptr1 moves to third node (node value=3), the ptr2 will move to fifth node (node value=5).

When the ptr2 reaches the NULL values, the position of ptr1 will be the output i.e. the middles of the given linked list.

If the Linked list is even then the algorithm will return 0 as an output.

These are the two methods you can try to find the middle of a given linked list.]

Below is the simple program:

node * middle(struct node *head)
struct node *first = head;
struct node *second = head;
if (head!=NULL)
while (first != NULL && first->next != NULL)
first = first->next->next;
second = second->next;
return second;
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version