-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMiddleOfTheLinkedList.java
59 lines (46 loc) · 1.23 KB
/
MiddleOfTheLinkedList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.leetcode.algorithms.easy.linkedlist;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
import com.leetcode.util.ListNode;
public class MiddleOfTheLinkedList {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String[] inputs = InputUtil.inputArr(scanner.next());
ListNode listNode = null;
for (int i = 0; i < inputs.length; i++) {
listNode = insertListNode(listNode, Integer.parseInt(inputs[i]));
}
// Output
System.out.println(middleNode(listNode).val);
scanner.close();
}
static ListNode insertListNode(ListNode listNode, int val) {
if (listNode == null) {
listNode = new ListNode(val);
} else {
listNode.next = insertListNode(listNode.next, val);
}
return listNode;
}
static ListNode middleNode(ListNode head) {
// If head is null
if (head == null) {
return null;
}
// Get middle of the node
ListNode temp = head;
int count = 1;
while(temp.next != null) {
temp = temp.next;
++count;
}
int middlePoint = count / 2;
int countMiddlePoint = 0;
while(countMiddlePoint < middlePoint) {
head = head.next;
++countMiddlePoint;
}
return head;
}
}