# 数据结构与算法 | Leetcode 876. middle-of-the-linked-list

image

## 求链表的中间结点

Leetcode 876. Middle of the Linked List

Input: [1,2,3,4,5]
Output: Node 3 from this list
Input: [1,2,3,4,5,6]
Output: Node 4 from this list

### 解法一

#### 代码

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
return null;
}
int len = 0;
for(ListNode curr = head; curr != null; ){
len++;
curr = curr.next;
}
int targetIndex = 0;
ListNode target = null;
for(ListNode curr = head; curr != null; ){
if(targetIndex == len / 2){
target = curr;
break;
}
targetIndex++;
curr = curr.next;
}
return target;
}
}

### 解法二

#### 代码

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {

return null;
}

for(ListNode curr = slow; slow != null; ){
if(fast == null || fast.next == null){
break;
}else{
fast = fast.next.next;
}
slow = slow.next;
}
return slow;
}
}

### 解法三

#### 代码

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {

return null;
}
int index = 0;
for(ListNode curr = head; curr != null; ){
if(index % 2 == 1){
target = target.next;
}
index++;
curr = curr.next;
}
return  target;
}
}