Skip to main content

Insert node at beginning of linked list in swift

Write a program which is create and add new node at the beginning of linked list in swift.

insert node at beginning of linked list

Here given of code implementation process.

/*
    Swift 4 program for
    Insert node at beginning of linked list
*/
// Linked list node
class LinkNode
{
    var data: Int;
    var next: LinkNode? ;
    init(_ data: Int, _ next: LinkNode? )
    {
        self.data = data;
        self.next = next;
    }
}
class SingleLL
{
    var head: LinkNode? ;
    init()
    {
        // Set inital value
        self.head = nil;
    }
    // Adding new node at beginning of linked list
    func addNode(_ data: Int)
    {
        // Create new node and set new head
        self.head = LinkNode(data, self.head);
    }
    // Display linked list element
    func display()
    {
        if (self.head == nil)
        {
            return;
        }
        var temp: LinkNode? = self.head;
        // iterating linked list elements
        while (temp  != nil)
        {
            print(temp!.data, terminator: " → ");
            // Visit to next node
            temp = temp!.next;
        }
        print(" NULL");
    }
}
func main()
{
    let sll: SingleLL = SingleLL();
    // Linked list
    // 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
    sll.addNode(8);
    sll.addNode(7);
    sll.addNode(6);
    sll.addNode(5);
    sll.addNode(4);
    sll.addNode(3);
    sll.addNode(2);
    sll.addNode(1);
    sll.display();
}
main();
 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 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.

New Comment