4-双向链表-Scala实现

import scala.util.control.Breaks.{break, breakable}

object DoubleLinkedListDemo {
  def main(args: Array[String]): Unit = {
    val doubleLinkedList = new DoubleLinkedList()
    val node1 = new HeroNode2(1,"宋江","及时雨")
    val node2 = new HeroNode2(2,"卢俊义","玉麒麟")
    val node3 = new HeroNode2(3,"吴用","智多星")
    val node4 = new HeroNode2(4,"林冲","豹子头")
    val node5 = new HeroNode2(4,"林小冲","豹子头")
    doubleLinkedList.add(node1)
    doubleLinkedList.add(node2)
    doubleLinkedList.add(node3)
    doubleLinkedList.add(node4)
    doubleLinkedList.list()
    println()

    doubleLinkedList.delete(4)
    doubleLinkedList.list()
  }
}
//添加,遍历,修改,删除
class DoubleLinkedList{
  val head = new HeroNode2(-1,"","")

  def add(heroNode: HeroNode2):Unit= {
    //1.先找到链表的最后节点
    //2.最后节点指向新节点


    //因为head不能动,我们一个辅助指针来定位
    var temp = head

    breakable {
      while (true) {
        if (temp.next == null) {
          break()
        }
        temp = temp.next
      }
    }

    temp.next = heroNode
    heroNode.pre = temp //双向
  }

  def isEmpty(): Boolean = {
    head.next == null
  }

  def list():Unit={
    if (isEmpty()){
      println("链表为空,无法遍历")
      return
    }

    var temp = head.next
    breakable {
      while (true) {
        //输出当前的节点的信息
        printf("no=%d name= %s nickname= %s", temp.no, temp.name, temp.nickname)
        println()
        if (temp.next == null) {
          break();
        } else {
          temp = temp.next
        }
      }
    }
  }
  def update(heroNode: HeroNode2):Unit={

    if (isEmpty()){
      println("链表为空~")
      return
    }
    //辅助指针,定位
    var temp = head.next
    //定义一个变量,表示是否找到该节点
    var flag = false
    breakable {
      while (true) {
        if (temp.no == heroNode.no) {
          flag = true
          break()
        }

        //判断temp 是不是到最后了
        if(temp.next == null){
          break()
        }

        temp = temp.next

      }
    }

    //判断
    if (flag){
      temp.name = heroNode.name
      temp.nickname = heroNode.nickname
    }else{
      printf("你要修改的%d英雄不存在",temp.no)
    }
  }

  //删除结点,因为双向链表可以自我删除,因此让temp指向要删除的结点
  def delete(no:Int): Unit ={
    if (isEmpty()){
      println("链表为空")
      return
    }
    var temp=head.next
    var flag = false
    breakable {
      while (true) {
        if (temp.no == no) {
          flag = true
          break()
        }

        if (temp.next == null) {
          break()
        }
        temp = temp.next
      }

    }
      //删除
      if(true){
          temp.pre.next = temp.next
        if (temp.next != null) {
          temp.next.pre = temp.pre
        }
      }else{
        printf("要删除的no=%d,不存在",no)
        println()
      }


  }

}
class HeroNode2(hNO:Int,hName:String,hNickname:String){

  val no = hNO
  var name = hName
  var nickname = hNickname
  var next: HeroNode2 =null //指向后一个节点
  var pre:HeroNode2 = null //指向前一个结点

}

  

posted @ 2020-05-20 00:19  济默  阅读(278)  评论(0编辑  收藏  举报