-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiddleOfLinkedList.java
More file actions
47 lines (41 loc) · 1.14 KB
/
MiddleOfLinkedList.java
File metadata and controls
47 lines (41 loc) · 1.14 KB
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
/**
* Leetcode problem #876, Middle of the Linked List
* https://leetcode.com/problems/middle-of-the-linked-list
*/
public class MiddleOfLinkedList {
public static void main(String[] args) {
ListNode list = prepareList(new int[] { 1, 2, 3, 4, 5, 6 });
ListNode midNode = middleNode(list);
System.out.println(midNode.val);
}
public static ListNode prepareList(int[] arr) {
ListNode currNode = new ListNode();
ListNode head = currNode;
for (int i : arr) {
currNode.next = new ListNode(i);
currNode = currNode.next;
}
return head.next;
}
public static ListNode middleNode(ListNode head) {
ListNode node = head;
while (node != null && node.next != null) {
node = node.next.next;
head = head.next;
}
return head;
}
static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}