Data Structure: Linked List in Swift 4
Motive
This post is all about learning linked list implementation in Swift. This post is strictly for those who are familiar with Swift and Linked list in general. So let’s get some hands-on it.
Creating Node
We have created Node class with value and next variables. It has a printNode method which prints all the nodes linked with it. Let’s create the Linked List class.
Creating Linked List Class
We have created Linked list class which has the parent node and the last node.
CreateLinkedListWithElements method creates the linked list with the given array.
Initializing Linked List
We have created linked list object with the integer array and then we print the linked list node by node
Appending Items in the linked list
Let’s write this method in the linked list class we created
Now use this method to append the elements to the linked list we create just before.
So appending elements to the linked list is quite easy.
Inserting a value in the Linked list
Write this method in the Linked list class.
Now let’s see how we can use it
As you can see, we inserted value 64 at index 8 in the list we created before. It inserts the value and prints the whole list node by node
Removing Node from Linked List
Let’s now remove a node from the linked list. Write this method in your Linked list class
Now let’s see how we can use it.
As you can see we have removed the node at position 2 which is 2 in this case and it prints all the node one by one after removal.
Get the last value
Let’s use it to get the value
Get Value at Index
Now let’s try to get the value at the given position.
Write this method in your linked list class
Let’s use this method to get the value at position 3 from the linked list we created.
Get the length of the linked list
Now let’s write the method in the Linked list class to get the length of the linked list.
Let’s use it.
Conclusion
That’s all the basic operations with the Linked list. Now you can try and do some advanced stuff with it like reversing a linked list etc. Try to implement a doubly linked list too, where a node has two pointers next and previous and use it with all the methods like reversing. That’s it, keep watching for the next data Structure I come up with. Thanks!