File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class MiddleOfLinkedList {
2
+
3
+ /**
4
+ * Definition for singly-linked list.
5
+ * public class ListNode {
6
+ * int val;
7
+ * ListNode next;
8
+ * ListNode() {}
9
+ * ListNode(int val) { this.val = val; }
10
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
11
+ * }
12
+ */
13
+
14
+ //Basic Approach: traverse till end of the list to find length and traverse till middle to find the middle of list
15
+ // class Solution {
16
+ // public ListNode middleNode(ListNode head) {
17
+ // ListNode temp = head;
18
+ // int len=0,i=0;
19
+ // while(temp!=null) {
20
+ // len++;
21
+ // temp=temp.next;
22
+ // }
23
+
24
+ // len=(len/2);
25
+ // temp=head;
26
+ // while(i<len) {
27
+ // temp=temp.next;
28
+ // i++;
29
+ // }
30
+ // return temp;
31
+ // }
32
+ // }
33
+
34
+ public class ListNode {
35
+ int val ;
36
+ ListNode next ;
37
+ ListNode () {}
38
+ ListNode (int val ) { this .val = val ; }
39
+ ListNode (int val , ListNode next ) { this .val = val ; this .next = next ; }
40
+ }
41
+
42
+ //Better Approach
43
+ // have 2 pointers fst pointer and slow pointer by the time fst pointer reaches end we know the middle
44
+
45
+ public ListNode middleNode (ListNode head ) {
46
+ if (head ==null ){
47
+ return head ;
48
+ }
49
+ ListNode fstptr =head , slwptr =head ;
50
+ while (fstptr !=null && fstptr .next !=null ) {
51
+ fstptr =fstptr .next .next ;
52
+ slwptr =slwptr .next ;
53
+ }
54
+
55
+ return slwptr ;
56
+ }
57
+
58
+ }
You can’t perform that action at this time.
0 commit comments