-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddlenode.java
More file actions
32 lines (26 loc) · 815 Bytes
/
Copy pathmiddlenode.java
File metadata and controls
32 lines (26 loc) · 815 Bytes
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
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class middlenode {
public static ListNode middleNode(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
fast=fast.next.next;
slow=slow.next; }
return slow;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
ListNode middle = middleNode(head);
System.out.println("The value of the middle node is: " + middle.val);
}
}
// time complexity-O(n)
// space complexity-O(1)