Monday, 15 June 2015

Scala Program: Reverse a linked list without using in built library function

Well, this is my first post in my blog.
I am a Scala enthusiast and find the language really interesting and tricky at times.
Its interesting if you write code in scala in scala way and not in java way as initially people coming from java background tends to do ( including me :) ).
Here, in this post i am sharing a program in scala to reverse a given Singly linked list.
In scala,you can do it in one line using in-built library function but i wanted to do it without that just like we do making node in java but in scala way,using its features. Here is my code,feel free to comment/add something.

object ReverseLinkedList {
  def main(args: Array[String]) {

    println("Program to reverse a given Singly linked List  " )
   var head =new Node(4)
    head.nxt=Some(new Node(5))
    head.nxt.get.nxt= Some(new Node(6))
    head.nxt.get.nxt.get.nxt= Some(new Node(7))
    head.nxt.get.nxt.get.nxt.get.nxt= Some(new Node(8))
    println("before reversal: ")
    var newHead = reverseNodes(Some(head), None)
    println("\n after reversal: ")
  def reverseNodes(  oldHead:Option[Node],  newHead:Option[Node]):Option[Node] = 
    oldHead match
      case None => newHead
      case x => { var tmpNext=x.get.nxt; x.get.nxt=newHead; reverseNodes(tmpNext , x) }
  def printNodes( head:Option[Node]):Unit = 
    head match
            case None => print("......finished")
            case x => { print("  "+x.get.num); printNodes(x.get.nxt) }
 class Node(var num:Int, var nxt:Option[Node]=None)
before reversal: 
  4  5  6  7  8......finished
 after reversal: 
  8  7  6  5  4......finished 

No comments:

Post a Comment