课程: Java Algorithms
今天就学习课程吧!
今天就开通帐号,24,700 门业界名师课程任您挑!
Solution: Detect a cylic linkedlist
- [Instructor] Let's create an algorithm that detects if a linked list has a cycle. Here we're given the ListNode class where each instance contains a piece of data and a next reference. In order to determine if a list has a cycle, we'll need to use these next pointers. We'll need to check that a given next pointer is not pointing to a node we've already seen in the list. This is a question of membership, which makes the hash set a great tool for this algorithm. In our function, we'll iterate through the linked list, and every time we see a new node, we'll check if it's in the hash set. If it's not, we'll add it to the set. If it is in the hash set, this means we've seen the node before and the list has a cycle. If we can get through the whole list without seeing the same node twice, we can be confident that the list does not have a cycle. Let's implement this idea in code. To start, we'll create a new hash set…
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。