Skip to content

Commit

Permalink
LC#876 returns middle node of linkedlist
Browse files Browse the repository at this point in the history
  • Loading branch information
NirmalSilwal committed Apr 10, 2022
1 parent 82922f6 commit 3816f72
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions Leetcode/leetcodeTags/LinkedList/MiddleOfLinkedList876.java
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;
}
}

0 comments on commit 3816f72

Please sign in to comment.