📌
100日アルゴリズム[13日目・片方向リスト]
問題
回答
/**
* 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)
* }
* }
*/
function hasCycle(head: ListNode | null): boolean {
if(head == null || head.next == null) {
return false
}
let front = head
let back = head
while(front.next !== null && back.next !== null && back.next.next !== null ) {
back = back.next.next
front = front.next
if (front == back) {
return true;
}
}
return false;
};
片方向リストの最後のnodeのnext値が配列内のメモリを示すpointerになっており、pointerがループしているかをチェックしています。
Discussion