Skip to content

Instantly share code, notes, and snippets.

@asethia
Created July 24, 2018 14:20
Show Gist options
  • Save asethia/69820038c266c1192355a481b3300a6f to your computer and use it in GitHub Desktop.
Save asethia/69820038c266c1192355a481b3300a6f to your computer and use it in GitHub Desktop.
Given a circular linked list, implement an algorithm that returns if loop exist
import org.scalatest.WordSpec
import scala.annotation.tailrec
/**
* Given a circular linked list, implement an algorithm that returns if loop exist
*
* Time Complexity O(n) and Space Complexity zero
*
* Created by Arun Sethia on 7/23/18.
*/
trait CircularLinklist {
/**
* abstract Node
*/
abstract class AbstractNode {
def data: Int
def next: AbstractNode
}
/**
* Nil Node to indicate end of link list
*/
object NilNode extends AbstractNode {
def data = -1
override def toString() = s"Nil"
lazy val next = throw new UnsupportedOperationException("tail of empty list")
}
/**
* Circular node in lazy way to keep next node
*
* @param data
* @param n
*/
class CircularNode(val data: Int, n: => AbstractNode) extends AbstractNode {
lazy val next = n
override def toString() = s"data: ${data} "
}
/**
* does loop exist or not
*
* @param node
* @return
*/
def isLoopExist(node: AbstractNode) = {
@tailrec
def loopTraverse(s: AbstractNode, f: AbstractNode): Boolean = {
if (f == NilNode || f.next == NilNode) false
else {
f.next.next match {
case NilNode => false
case n: AbstractNode => {
if (s == f) true
else loopTraverse(s.next, f.next.next)
}
}
}
}
if (node == NilNode || node.next == NilNode) false
else loopTraverse(node, node.next)
}
}
object LinklistLoopDetect extends App with CircularLinklist{
val node1: AbstractNode = new CircularNode(1, node2)
val node2: AbstractNode = new CircularNode(2, node3)
val node3: AbstractNode = new CircularNode(3, node4)
val node4: AbstractNode = new CircularNode(4, node5)
val node5: AbstractNode = new CircularNode(5, node2)
val isCirculer=isLoopExist(node1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment