Written interview questions: Determine whether there is a ring in a singly linked list

       Originally published in:

 

      I encountered such a problem in the written test of U company before:

       Determine whether the singly linked list has a ring.

 

      Let's first look at such a common sense: What is the difference between the loop in reality and the loop of a singly linked list? 

      Obviously: The loop in reality can have two directions, either loop or escape. However, in a singly linked list, the pointer next can only point to one point, so the circular linked list must circulate forever and there is no exit. As shown below:

 

      Back to the question itself, how to judge whether a singly linked list has a ring?

 

Algorithm 1: Notation

      The easiest thing to think of is definitely notation. When traversing the linked list, record the visited nodes. If it is a circular singly linked list, there must be nodes to be visited repeatedly. This kind of thinking is very natural.

      When marking, you can consider using hash map or hash set, which will consume some space. Since the thinking is relatively clear, there is no need to introduce the procedures in detail.

 

Algorithm 2: Brute force algorithm

      Violence is also a way of solving problems, although not necessarily the best way.

     Think about it this way: if you go all the way to black, if you reach the end, then there is no ring, if you don’t reach the end, it means you keep going around in the ring.

     I did this topic on Leetcode just now, using the brute force method, which can pass all test cases. The code is as follows:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func hasCycle(head *ListNode) bool {

    count := 0
    max := 12000
    for ; head != nil && count < max; {
        count++
        head = head.Next
    }

    if count == max {
        return true
    }

    return false
}

      At first glance, this brute force algorithm has limitations: for example, if the linked list is long enough, it will also cause count and max to be equal, which may lead to misjudgment.

 

Algorithm 3: Fast and slow pointers

      The motorcycle is behind, the bicycle is in front, and the motorcycle is chasing the bicycle. If it is a ring road with no way out, then the motorcycle will inevitably catch up with the bicycle.

      Therefore, we can adopt a similar idea, let the fast pointer be in the back, and the slow pointer in the front, to determine whether the singly linked watch has a ring. The advantage of this method is that the space complexity is O(1) and there will be no misjudgments.

      Now that you know the idea, writing a program is a very simple matter, so I won't repeat it.

 

 

      Have a nice weekend, talk to you next week, see or leave.

Guess you like

Origin blog.csdn.net/stpeace/article/details/109544019