-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiddleOfLinkedList.java
More file actions
58 lines (50 loc) · 1.51 KB
/
Copy pathMiddleOfLinkedList.java
File metadata and controls
58 lines (50 loc) · 1.51 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
48
49
50
51
52
53
54
55
56
57
58
public class MiddleOfLinkedList {
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
//Basic Approach: traverse till end of the list to find length and traverse till middle to find the middle of list
// class Solution {
// public ListNode middleNode(ListNode head) {
// ListNode temp = head;
// int len=0,i=0;
// while(temp!=null) {
// len++;
// temp=temp.next;
// }
// len=(len/2);
// temp=head;
// while(i<len) {
// temp=temp.next;
// i++;
// }
// return temp;
// }
// }
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
//Better Approach
// have 2 pointers fst pointer and slow pointer by the time fst pointer reaches end we know the middle
public ListNode middleNode(ListNode head) {
if(head==null){
return head;
}
ListNode fstptr=head, slwptr=head;
while(fstptr!=null && fstptr.next!=null) {
fstptr=fstptr.next.next;
slwptr=slwptr.next;
}
return slwptr;
}
}