What is a cycle/loop in the singly-linked list?
What is a cycle/loop in the singly-linked list?
A cycle or loop in a singly-linked list occurs when a node in the list points back to a previous node, creating a closed loop. This means that by continuously following the next
pointers, you will eventually revisit the same node, rather than reaching the end of the list (which would normally be indicated by a NULL
pointer).
next
pointer[2][3][7].slow
and fast
. The slow
pointer moves one step at a time, while the fast
pointer moves two steps at a time. If there is a cycle, the fast
pointer will eventually meet the slow
pointer[4][7][9].head = [3,2,0,-4]
, pos = 1
true
head = [1][2]
, pos = 0
true
head = [1]
, pos = -1
false
def has_cycle(head):
visited = set()
current = head
while current:
if current in visited:
return True
visited.add(current)
current = current.next
return False
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào