package datastructure.linkedList
import scala.util.control.Breaks
class DoubleLinkedList {
//先初始化一个头节点
private val head = new HeroNode2(0,"","")
/**
* 展示双向链表
*/
def show(): Unit = {
if(head.next == null){
println("链表为空")
return
}
var temp = head.next
val control = new Breaks
//遍历链表找到最后
control.breakable(
while (true){
//找到链表的最后
if(temp == null){
control.break()
}
//没有找到最后就后移
println(temp)
temp = temp.next
}
)
}
/**
* 添加节点到双向链表最后
* @param node 待添加的节点
*/
def add(node: HeroNode2): Unit = {
//当不考虑编号的顺序,找到链表的最后节点,将next指向node这个节点
var temp = head
val control = new Breaks
//遍历链表找到最后
control.breakable(
while (true){
//找到链表的最后
if(temp.next == null){
control.break()
}
//没有找到最后就后移
temp = temp.next
}
)
//形成双向链表
temp.next = node
node.pre = temp
}
/**
* 根据no来修改节点信息,和单向链表一样
* @param node 修改的节点
*/
def update(node: HeroNode2): Unit = {
if(head.next == null) {
println("链表为空")
return
}
var temp = head.next
var flag = false //表示是否找到节点
val control = new Breaks
//遍历链表找到最后
control.breakable(
while (true){
//找到链表的最后
if(temp.next == null){
control.break()
}
if(temp.no == node.no){
flag = true
control.break()
}
temp = temp.next
}
)
if(flag){
temp.name=node.name
temp.nickName=node.nickName
} else {
println(s"没有找到该节点${node.no}")
}
}
/**
* 找到待删除节点,自我删除
* @param node 待删除节点
*/
def delete(node: HeroNode2): Unit = {
if (head.next == null){
println("空链表,无法删除")
return
}
var temp = head.next
var flag = false
val control = new Breaks
control.breakable(
while (true){
if(temp == null){ //链表最后
control.break()
}
if(temp.no == node.no ){//找到该节点
flag = true
control.break()
}
temp = temp.next
}
)
if(flag) {
temp.pre.next = temp.next
//如果是最后一个节点,可能会有空引用
if(temp.next != null){
temp.next.pre = temp.pre
}
}
else {
println(s"没有找到该节点${node.no}")
}
}
}
class HeroNode2{
var pre: HeroNode2 = _ //指向前一个结点
var next: HeroNode2 = _ //指向下一个结点
var no: Int = _
var name: String = _
var nickName: String = _
def this(hNo: Int, name: String,nick: String) = {
this()
this.no = hNo
this.name = name
this.nickName = nick
}
override def toString: String = {
s"HeroNode{no=$no, name= $name, nickName= $nickName}"
}
}
object DoubleLinkedListDemo{
def main(args: Array[String]): Unit = {
println("双向链表测试")
val hero1 = new HeroNode2(1, "宋江", "及时雨")
val hero2 = new HeroNode2(2, "卢俊义", "玉麒麟")
val hero3 = new HeroNode2(3, "林冲", "豹子头")
val hero4 = new HeroNode2(4, "吴用", "智多星")
val list = new DoubleLinkedList()
list.add(hero1)
list.add(hero2)
list.add(hero3)
list.add(hero4)
list.show()
println("修改测试")
val hero5 = new HeroNode2(2, "小卢", "玉麒麟~~")
list.update(hero5)
list.show()
println("删除测试")
list.delete(node = hero4)
list.show()
}
}
java双向链表
最新推荐文章于 2024-08-10 17:57:54 发布