> For the complete documentation index, see [llms.txt](https://soumyajit4419.gitbook.io/ds-algo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://soumyajit4419.gitbook.io/ds-algo/linked-list/middle-of-the-linked-list.md).

# 8.Middle of the Linked List

### Solution I

```cpp
class Solution
{
public:
    ListNode *middleNode(ListNode *head)
    {

        if (head == NULL)
        {
            return head;
        }

        ListNode *p = head;
        ListNode *q = head;
        int s = 0;
        while (p != NULL)
        {
            s = s + 1;
            p = p->next;
        }

        int mid = s / 2;

        int i = 0;
        while (i < mid)
        {
            i++;
            q = q->next;
        }
        cout << q->val;
        return q;
    }
}
```

This approach has a **time complexity of O(n)** but we need to iterate the list a number of times.

### Solution II (Using two pointers)

```cpp
class Solution
{
public:
    ListNode *middleNode(ListNode *head)
    {

        ListNode *p = head;
        ListNode *q = head;

        while (p!= NULL && p->next != NULL)
        {
            p = p->next->next;
            q = q->next;
        }
        
        return q;
    }
};
```

This solution is using **fast pointer and slow pointer**. **Time Complexity O(n).**
