Insert node at end of linked list in swift

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

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

``````// Swift 4 Program for
// Insert linked list element at end position

{
var data: Int;
init(_ data: Int)
{
self.data = data;
self.next = nil;
}
}
class SingleLL
{
init()
{
}
{
// Create new node
{
}
else
{
// Find the last node
while (temp!.next  != nil)
{
// Visit to next node
temp = temp!.next;
}
// Add node at last position
temp!.next = node;
}
}
// Display all Linked List elements
func display()
{
{
while (temp  != nil)
{
// Display node value
print(temp!.data, terminator: "  ");
// Visit to next node
temp = temp!.next;
}
}
else
{
}
}
}
func main()
{
let sll: SingleLL = SingleLL();
// 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
sll.display();
}
main();``````
`````` 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.

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

{
var data: Int;
init(_ data: Int)
{
self.data = data;
self.next = nil;
}
}
class SingleLL
{
init()
{
self.tail = nil;
}
{
// Create a new node
{
}
else
{
self.tail!.next = node;
}
self.tail = node;
}
func display()
{
{
return;
}
while (temp  != nil)
{
print(temp!.data , terminator: " → ");
// Visit to next node
temp = temp!.next;
}
print(" NULL");
}
}
func main()
{
let sll: SingleLL = SingleLL();
// 10 → 20 → 30 → 40 → 50 → NULL
sll.display();
}
main();``````
``````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.