
SWIFT – Print elements of Linked List in Reverse Order
Hey Folks! Today we will be doing a challenge to print out the elements of a linked list in reverse order in Swift
First of all, If you do not have a Linked List created in your playground, go to my Linked List In Swift blog post and copy the code.
Now let’s dive directly into the code.
First, we will create a linked list and append some data to it.
import Foundation //1 var list = LinkedList<Int>() //2 func addDataToList() { list.append(5) list.append(6) list.append(1) list.append(3) list.append(4) list.append(6) } addDataToList()
Approach 1
Now once we have added the data, let’s start writing our reverse function. Start writing down the code below the addDataToList()
function call.
//1 // create a function that prints out the element of a linked list in reverse order func reverseList<T>( _ list : LinkedList<T>) -> String { //2 guard let _ = list.head else { return "Empty List" } //3 var current = list.head var reverseString = "" //4 repeat { reverseString = "\(current!.value) " + reverseString current = current?.next } while (current != nil) return reverseString } print("BEFORE: ",list) print("AFTER: ", reverseList(list))
Here is what we have done in the above code.
- We start the code by creating a generic function named
reverseList
that takes a linked list as a parameter and returns a string. - With help of a
guard
statement, we check if the head node of the list is not empty. If it isnil
, then the else block will be executed and will return Empty List. - Once we have checked that the list is not empty, we declare two variables named
current
andreverseString
.reverseString
will hold the final reverse string andcurrent
will be used to traverse the list by incrementing its position after every loop. - We are using a repeat-while loop which is swift equivalent to do while loop. In the repeat while loop, we are traversing through all the elements of the linked list. We add the
current
value to the beginning of the reverse string and then change the position ofcurrent
tocurrent?.next
. We can also force unwrap the value ofcurrent
inrepeat-while loop
as we knowcurrent
will never be nil inside the block. The while loop will keep running until current is not equal to nil.
It’s time now to run the code and check if it’s working. Write a print statement to check if the function is working. Run the playground and you will see this output in the console.
BEFORE: 5 --> 6 --> 1 --> 3 --> 4 --> 6 AFTER: 6 4 3 1 6 5
Approach 2
In this approach, we will reverse the linked list and print it. If you are preparing for interviews, this approach would interest the interviewer more. Lets write down the code.
The trick to reverse a linked list is to just point next position of the node to previous. Example: 5->6->7->8->9->nil now instead of changing the position of the node., we will just change the arrows to point to previous nodes i.e. 5<-6<-7<-8<-9 and change the head to 9.
func reverse<T>(llist: Node<T>?) -> Node<T>? { //1 Write your code here // check for nil if llist == nil { return nil } //2 check if only element if llist?.next == nil { return llist } //3 check for multiple elements var head = llist var prev : Node<T>? = nil var current = llist var next = llist?.next //4 while next != nil { current?.next = prev prev = current current = next next = current?.next } //5 current?.next = prev head = current return head } //6 print("REVERSE: ", reverse(llist: list.head) as Any)
So let’s understand how the code above works.
- First we will check if the given linked list is not equal to list. If it equals to
nil
,return nil
from the function. - Next we check if the list only contains one node. If
true
, return the same as reverse of one node will be the same node itself. - Now we check for multiple elements. Here we are declaring some variables to store the
current, previous, next
andhead
position. We have set the initial value ofprev = nil
as there is nothing previous tohead
. - Now we will start a
while
loop tillnext
is not equal tonil
and keep increasing the position ofnext
to its next node. We will swap values of current previous and next as shown in the code. - The while loop only run till
next != nil
. That means the tail node which is currently assigned tocurrent
node is still not traveresed. We will assign thetail(current?.next = prev)
index of its previous node and make the tail as head. - Finally print the list.
//OUTPUT LIST: 1 --> 2 --> 3 --> 4 --> 5 --> 6 --> 7 REVERSE: 7 --> 6 --> 5 --> 4 --> 3 --> 2 --> 1
Both the approaches above work perfectly. If you have any other issues, please reach out in the comments.