Insert node at end of linked list in scala

Write a program which is create and add linked list node at the end (tail, last) position in scala.

Suppose we are inserted the following (10, 20, 30 ,40 ,50) node in a sequence.

``````// Scala Program for
// Insert linked list element at end position Set A

// Linked list node
class LinkNode(var data: Int,
{
def this(data: Int)
{
this(data, null);
}
}
{
def this()
{
this(null);
}
// Add new node at the end of linked list
def addNode(value: Int): Unit = {
// Create new node
if (this.head == null)
{
}
else
{
// find last node
while (temp.next != null)
{
// Visit to next node
temp = temp.next;
}
// Add node at last position
temp.next = node;
}
}
//Display all Linked List elements
def display(): Unit = {
if (this.head != null)
{
while (temp != null)
{
// Display node value
print("  " + temp.data);
// Visit to next node
temp = temp.next;
}
}
else
{
}
}
}
object Main
{
def main(args: Array[String]): Unit = {
var sll: SingleLL = new SingleLL();
// 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
print(" Linked List \n");
sll.display();
}
}``````
`````` Linked List
1  2  3  4  5  6  7  8``````

Time complexity of above program is O(n). We can optimize above algorithm using one extra pointer. Which is hold the reference of last node. Below are implementation of this logic.

``````// Scala Program for
// Insert linked list element at end position set B

// Linked list node
class LinkNode(var data: Int,
{
def this(data: Int)
{
this(data, null);
}
}
{
def this()
{
this(null, null);
}
// Add new node at the end of linked list
def addNode(value: Int): Unit = {
// Create a new node
if (this.head == null)
{
}
else
{
this.tail.next = node;
}
this.tail = node;
}
// Display linked list element
def display(): Unit = {
if (this.head == null)
{
return;
}
// iterating linked list elements
while (temp != null)
{
print(""+ temp.data + " → ");
// Visit to next node
temp = temp.next;
}
print(" NULL\n");
}
}
object Main
{
def main(args: Array[String]): Unit = {
var sll: SingleLL = new SingleLL();
// 10 → 20 → 30 → 40 → 50 → NULL
sll.display();
}
}``````
``````Linked List
10 → 20 → 30 → 40 → 50 →  NULL``````

Time complexity of above program is O(1).

Comment

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.