Saturday, March 4, 2023
n
is a length of a list/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func middleNode(head *ListNode) *ListNode {
slow, fast := head, head
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
}
return slow
}
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
n
is a length of a listfunction middleNode(head: ListNode | null): ListNode | null {
if (!head.next) {
return head;
}
let length = 0;
let current = head;
while (current) {
current = current.next;
length++;
}
current = head;
for (let i = 0 ; i < Math.floor(length/2) ; i++){
current = current.next;
}
return current;
};
n
is a length of a listn
is a length of a listfunction middleNode(head: ListNode | null): ListNode | null {
const nodes: ListNode[] = [];
while (head != null) {
nodes.push(head);
head = head.next;
}
const midIndex = Math.floor(nodes.length / 2);
return nodes[midIndex];
};
n
is a length of a listfunction middleNode(head: ListNode | null): ListNode | null {
let slow = head;
let fast = head;
while (fast && fast.next){
slow = slow.next;
fast = fast.next.next;
}
return slow;
};