Skip to content

Commit e17a194

Browse files
authored
Create Middle of the Linked List
1 parent 71360e4 commit e17a194

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Middle of the Linked List

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
class Solution {
10+
public ListNode middleNode(ListNode head) {
11+
if(head.next == null){
12+
return head;
13+
}
14+
else if(head.next.next == null){
15+
return head.next;
16+
}
17+
ListNode fast = head;
18+
ListNode slow = head;
19+
int count = 0;
20+
while(fast.next != null && fast.next.next != null){
21+
fast = fast.next.next;
22+
slow = slow.next;
23+
count += 2;
24+
if(fast.next == null){
25+
count--;
26+
}
27+
}
28+
29+
if(count % 2 == 0){
30+
return slow.next;
31+
}
32+
return slow;
33+
}
34+
}

0 commit comments

Comments
 (0)