Count frequency of a key in doubly linked list in scala
Scala program for Count frequency of a key in doubly linked list. Here more information.
// Scala program for
// Count frequency of given node in doubly linked list
class LinkNode(var data: Int,
var next: LinkNode,
var prev: LinkNode)
{
def this(data: Int)
{
this(data, null, null);
}
}
class DoublyLinkedList(var head: LinkNode,
var tail: LinkNode)
{
def this()
{
this(null, null);
}
// Insert new node at end position
def insert(value: Int): Unit = {
// Create a node
var node: LinkNode = new LinkNode(value);
if (this.head == null)
{
// Add first node
this.head = node;
this.tail = node;
return;
}
// Add node at last position
this.tail.next = node;
node.prev = this.tail;
this.tail = node;
}
// Display node element of doubly linked list
def display(): Unit = {
if (this.head == null)
{
println("Empty Linked List");
}
else
{
print("Linked List Head to Tail :");
// Get first node of linked list
var temp: LinkNode = this.head;
// iterate linked list
while (temp != null)
{
// Display node value
print(" " + temp.data);
// Visit to next node
temp = temp.next;
}
print("\nLinked List Tail to Head :");
// Get last node of linked list
temp = this.tail;
// iterate linked list
while (temp != null)
{
// Display node value
print(" " + temp.data);
// Visit to prev node
temp = temp.prev;
}
print("\n");
}
}
// Count frequency of given node
def frequency(key: Int): Unit = {
var result: Int = 0;
var temp: LinkNode = this.head;
while (temp != null)
{
if (temp.data == key)
{
// count key
result += 1;
}
// Visit to next node
temp = temp.next;
}
// Print result
println("Frequency of node " + key + " is : " + result);
}
}
object Main
{
def main(args: Array[String]): Unit = {
var dll: DoublyLinkedList = new DoublyLinkedList();
// Insert following linked list nodes
dll.insert(7);
dll.insert(2);
dll.insert(3);
dll.insert(4);
dll.insert(5);
dll.insert(3);
dll.insert(7);
dll.insert(3);
//display all node
dll.display();
dll.frequency(3);
dll.frequency(11);
dll.frequency(7);
}
}
Output
Linked List Head to Tail : 7 2 3 4 5 3 7 3
Linked List Tail to Head : 3 7 3 5 4 3 2 7
Frequency of node 3 is : 3
Frequency of node 11 is : 0
Frequency of node 7 is : 2
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment