6
6
7
7
<p >Given a non-empty, singly  ; linked list with head node <code >head</code >, return  ; a  ; middle node of linked list.</p >
8
8
9
-
10
-
11
9
<p >If there are two middle nodes, return the second middle node.</p >
12
10
13
-
14
-
15
11
<p >  ; </p >
16
12
17
-
18
-
19
13
<div >
20
14
21
15
<p ><strong >Example 1:</strong ></p >
22
16
23
-
24
-
25
17
<pre >
26
18
27
19
<strong >Input: </strong ><span id =" example-input-1-1 " >[1,2,3,4,5]</span >
@@ -36,14 +28,10 @@ ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = N
36
28
37
29
</pre >
38
30
39
-
40
-
41
31
<div >
42
32
43
33
<p ><strong >Example 2:</strong ></p >
44
34
45
-
46
-
47
35
<pre >
48
36
49
37
<strong >Input: </strong ><span id =" example-input-2-1 " >[1,2,3,4,5,6]</span >
@@ -54,16 +42,10 @@ Since the list has two middle nodes with values 3 and 4, we return the second on
54
42
55
43
</pre >
56
44
57
-
58
-
59
45
<p >  ; </p >
60
46
61
-
62
-
63
47
<p ><strong >Note:</strong ></p >
64
48
65
-
66
-
67
49
<ul >
68
50
<li>The number of nodes in the given list will be between <code>1</code> and <code>100</code>.</li>
69
51
</ul >
@@ -72,22 +54,49 @@ Since the list has two middle nodes with values 3 and 4, we return the second on
72
54
73
55
</div >
74
56
75
-
76
-
77
57
## Solutions
78
58
79
59
<!-- tabs:start -->
80
60
81
61
### ** Python3**
82
62
83
63
``` python
84
-
64
+ # Definition for singly-linked list.
65
+ # class ListNode:
66
+ # def __init__(self, val=0, next=None):
67
+ # self.val = val
68
+ # self.next = next
69
+ class Solution :
70
+ def middleNode (self , head : ListNode) -> ListNode:
71
+ slow = fast = head
72
+ while fast and fast.next:
73
+ slow, fast = slow.next, fast.next.next
74
+ return slow
85
75
```
86
76
87
77
### ** Java**
88
78
89
79
``` java
90
-
80
+ /**
81
+ * Definition for singly-linked list.
82
+ * public class ListNode {
83
+ * int val;
84
+ * ListNode next;
85
+ * ListNode() {}
86
+ * ListNode(int val) { this.val = val; }
87
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
88
+ * }
89
+ */
90
+ class Solution {
91
+ public ListNode middleNode (ListNode head ) {
92
+ ListNode slow = head, fast = head;
93
+ while (fast != null && fast. next != null ) {
94
+ slow = slow. next;
95
+ fast = fast. next. next;
96
+ }
97
+ return slow;
98
+ }
99
+ }
91
100
```
92
101
93
102
### ** ...**
0 commit comments