find the length of a linked list in swift

To find the length of a linked list in Swift, we need to traverse through the linked list and count the number of nodes present in it. Here is the Swift code to achieve this:

main.swift
func lengthOfLinkedList(head: ListNode?) -> Int {
    var count = 0
    var current = head
    while current != nil {
        count += 1
        current = current!.next
    }
    return count
}
194 chars
10 lines

In the above code, we are initializing a count variable to 0 and a current variable to the head of the linked list. We use a while loop to iterate through the linked list and count the number of nodes present in it. Inside the while loop, we increment the count by 1 and move to the next node by setting the current variable to its next node. We continue this until we reach the end of the linked list (i.e., the current variable is nil).

Finally, we return the count variable which contains the length of the linked list.

gistlibby LogSnag