File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
Leetcode/leetcodeTags/LinkedList Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ package LinkedList ;
2+
3+ public class MiddleOfLinkedList876 {
4+
5+ public class ListNode {
6+ int val ;
7+ ListNode next ;
8+
9+ ListNode () {
10+ }
11+
12+ ListNode (int val ) {
13+ this .val = val ;
14+ }
15+
16+ ListNode (int val , ListNode next ) {
17+ this .val = val ;
18+ this .next = next ;
19+ }
20+ }
21+
22+ public ListNode middleNode (ListNode head ) {
23+ ListNode temp = head ;
24+ int length = 1 ;
25+
26+ while (temp .next != null ) {
27+ temp = temp .next ;
28+ length ++;
29+ }
30+ int count = 0 ;
31+ ListNode temp2 = head ;
32+
33+ while (count < length / 2 ) {
34+ temp2 = temp2 .next ;
35+ count ++;
36+ }
37+ return temp2 ;
38+ }
39+
40+ // 2nd approach
41+ public ListNode middleNode2 (ListNode head ) {
42+ ListNode slow = head ;
43+ ListNode fast = head ;
44+
45+ while (fast != null && fast .next != null ) {
46+ slow = slow .next ;
47+ fast = fast .next .next ;
48+ }
49+
50+ return slow ;
51+ }
52+ }
You can’t perform that action at this time.
0 commit comments