def middle_node(head):
slow=fast=head
while fast and fast.next:
slow=slow.next; fast=fast.next.next
return slow
public ListNode middleNode(ListNode head){
ListNode slow=head,fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next; fast=fast.next.next;
} return slow;
}
Fast/slow pointer. Truthiness vs null checks.
def middle_node(head):
slow=fast=head
while fast and fast.next:
slow=slow.next; fast=fast.next.next
return slow
public ListNode middleNode(ListNode head){
ListNode slow=head,fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next; fast=fast.next.next;
} return slow;
}
1. Fast 2x speed 2. Fast ends -> slow is middle