# Introduction to algorithm C-876. Intermediate node of linked list

LeetCode problem brushing - algorithm learning plan (Introduction)

# Introduction of ideas

My idea: first obtain the length len of the linked list, and the len / 2 + 1 node is the intermediate node (starting from 1)

The official provides the fast and slow pointer method. I think it's good. See the following for details.

# My first correct submission

```/**
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/

{
int len = 1;
if(tmp == NULL)
return 0;
while(tmp->next != NULL)
{
len++;
tmp = tmp->next;
}
return len;
}

{
int i = 0;
for(i = 1; i < len / 2 + 1; i++)  //len / 2 + 1 is the intermediate node serial number (starting from 1)
{
tmp = tmp->next;
}
return tmp;
}
```

# Official version

Here is the official idea

## Method 1: array

The disadvantage of the linked list is that the corresponding elements cannot be accessed through subscripts. Therefore, we can consider traversing the linked list and putting the traversed elements into array A in turn. If we traverse n elements, the length of the linked list and array is also N, and the corresponding intermediate node is A[N/2].
——Author: leetcode solution

```The official didn't give it C Language version, but I won't look for it. Just have ideas.

```

Complexity analysis
Time complexity: O(N), where N is the number of nodes in a given linked list.
Space complexity: O(N), that is, the space used by array A.

## Method 2: single pointer method

We can optimize the space of method 1 and omit array A.
We can traverse the linked list twice. During the first traversal, we count the number of elements n in the linked list; In the second traversal, when we traverse to the N/2 element (the first node of the linked list is the 0 element), we can return the element.
——Author: leetcode solution

Paste an official C + + version:

```class Solution {
public:
int n = 0;
while (cur != nullptr) {
++n;
cur = cur->next;
}
int k = 0;
while (k < n / 2) {
++k;
cur = cur->next;
}
return cur;
}
};

Author: LeetCode-Solution
Source: force buckle( LeetCode)
```

Complexity analysis
Time complexity: O(N), where N is the number of nodes in a given linked list.
Space complexity: O(1), only constant space is needed to store variables and pointers.

## Method 3: fast and slow pointer method

We can continue to optimize method 2 and use two pointers slow and fast to traverse the linked list. Slow takes one step at a time and fast takes two steps at a time. Then when fast reaches the end of the linked list, slow must be in the middle.
——Author: leetcode solution

Paste an official C + + version:

```class Solution {
public:
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};

Author: LeetCode-Solution