LinkedList in DataStructures using Kotlin..........................


   THIS SAME CODE I WROTE IN JAVA BUT THE LENGTH OF CODE
        WAS DOUBLE AS COMPARED TO THIS CODE(In kotlin)
class Node internal constructor(var data: String) {
    @JvmField    var next: Node? = null    
    @JvmField    var previous: Node? = null}
package com.company
class LinkedList internal constructor() {
    protected var head: Node? = null
    protected var tail: Node? = null
    var size = 0        
protected set    val isEmpty: Boolean
        get() = size == 0
    fun showAllForward() {
        if (head == null) return else {
            var curr = head
            while (curr != null) {
                println(curr.data)
                curr = curr.next            }
        }
    }
    fun showAllBackward() {
        if (tail == null) return else {
            var curr = tail
            while (curr != null) {
                println(curr.data)
                curr = curr.previous            }
        }
    }
    fun insertAtFirst(data: String?) {
        val curr = Node(data!!)
        if (tail == null) tail = curr else {
            head!!.previous = curr
 //is par tail bhi curr ban jaye ga
        }
        curr.next = head
        head = curr
        size++
    }
    fun insertAtEnd(name: String?) {
        val curr = Node(name!!)
        if (head == null) head = curr else {
            tail!!.next = curr
            curr.previous = tail        }
        tail = curr
        size++
    }
    init {
        size = 0    }
}
object Main {
    @JvmStatic    fun main(args: Array<String>) {
        val list = LinkedList()
        list.insertAtFirst("Fahad Shahzad") //1
        list.insertAtFirst("M Yamin") //1
        list.insertAtFirst("Programmer Warrior") //1
        //        list.showAllBackward();
        list.showAllForward()
        println("The size of LinkedList is = ${list.size}")
    }
}

Comments

Post a Comment

Let me know your doubts

Popular Posts