-
-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
LC#876 returns middle node of linkedlist
- Loading branch information
1 parent
82922f6
commit 3816f72
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
52 changes: 52 additions & 0 deletions
52
Leetcode/leetcodeTags/LinkedList/MiddleOfLinkedList876.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package LinkedList; | ||
|
||
public class MiddleOfLinkedList876 { | ||
|
||
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; | ||
} | ||
} | ||
|
||
public ListNode middleNode(ListNode head) { | ||
ListNode temp = head; | ||
int length = 1; | ||
|
||
while (temp.next != null) { | ||
temp = temp.next; | ||
length++; | ||
} | ||
int count = 0; | ||
ListNode temp2 = head; | ||
|
||
while (count < length / 2) { | ||
temp2 = temp2.next; | ||
count++; | ||
} | ||
return temp2; | ||
} | ||
|
||
// 2nd approach | ||
public ListNode middleNode2(ListNode head) { | ||
ListNode slow = head; | ||
ListNode fast = head; | ||
|
||
while (fast != null && fast.next != null) { | ||
slow = slow.next; | ||
fast = fast.next.next; | ||
} | ||
|
||
return slow; | ||
} | ||
} |