reverse a single linked list in swift

To reverse a single linked list in Swift, you can follow the below steps:

  1. Define a Node class to represent each node in the linked list. Each node holds a value and a reference to the next node.
main.swift
class Node<T> {
    var value: T
    var next: Node<T>?
    
    init(value: T) {
        self.value = value
        self.next = nil
    }
}
141 chars
10 lines
  1. Define a LinkedList class to represent the linked list. This class holds a reference to the head node of the list.
main.swift
class LinkedList<T> {
    var head: Node<T>?
    
    // Insert and other linked list operations
}
99 chars
6 lines
  1. Write a function that reverses the linked list. This function modifies the next pointers of each node to reverse the direction of the list.
main.swift
func reverse() {
    var prev: Node<T>? = nil
    var current = head
    var next: Node<T>? = nil
    
    while current != nil {
        next = current?.next
        current?.next = prev
        prev = current
        current = next
    }

    head = prev
}
259 chars
15 lines
  1. To test the linked list reversal, you can create a linked list with some values and call the reverse function.
main.swift
let list = LinkedList<Int>()
list.insert(1)
list.insert(2)
list.insert(3)

list.reverse()

// The list now contains 3 -> 2 -> 1
128 chars
9 lines

The final implementation of the LinkedList class with the reverse function should look like this:

main.swift
class LinkedList<T> {
    var head: Node<T>?

    func insert(_ value: T) {
        let newNode = Node(value: value)
        if head == nil {
            head = newNode
        } else {
            var current = head
            while current?.next != nil {
                current = current?.next
            }
            current?.next = newNode
        }
    }

    func reverse() {
        var prev: Node<T>? = nil
        var current = head
        var next: Node<T>? = nil
        
        while current != nil {
            next = current?.next
            current?.next = prev
            prev = current
            current = next
        }

        head = prev
    }
}
678 chars
32 lines

gistlibby LogSnag