标签:let pre 输出 flag 编号 标识 定义 unit bool
今天学习了单向链表的实现,记录一下,方便以后查看~
import util.control.Breaks._ object SingleLinkedListDemo { def main(args: Array[String]): Unit = { //创建和遍历 val singleLinkedList = new SingleLinkedList() val node1 = new HeroNode(1,"宋江","及时雨") val node2 = new HeroNode(4,"卢俊义","玉麒麟") val node3 = new HeroNode(2,"吴用","智多星") val node4 = new HeroNode(3,"林冲","豹子头") singleLinkedList.addByOrder(node1) singleLinkedList.addByOrder(node2) singleLinkedList.addByOrder(node3) singleLinkedList.addByOrder(node3) singleLinkedList.addByOrder(node4) singleLinkedList.list() } } class SingleLinkedList{ //创建头节点,指向该链表的头部 val head = new HeroNode(-1,"","") //添加英雄到链表 //默认加到链表的最后 def add(heroNode: HeroNode):Unit= { //1.先找到链表的最后节点 //2.最后节点指向新节点 //因为head不能动,我们一个辅助指针来定位 var temp = head breakable { while (true) { if (temp.next == null) { break() } temp = temp.next } } temp.next = heroNode } def addByOrder(heroNode: HeroNode):Unit={ //让temp指向head var temp = head var flag = false //标识是否已经存在编号的节点 //将temp定位到要添加节点的前一个位置 breakable { while (true) { //判断是否已经到最后一个 if (temp.next == null) { break() } if (temp.next.no == heroNode.no) { //说明no已经存在 flag = true break() } else if (temp.next.no > heroNode.no) { //说明heronode,就添加到这 break() } //将temp后移实现遍历 temp = temp.next } } if (flag){ printf("已经存在n0=%d 人物",heroNode.no) println() }else{ heroNode.next = temp.next temp.next = heroNode } } //遍历单项链表 //1.用temp遍历 //2.判断链表是否为空,为空就退出;不为空。就遍历 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 isEmpty():Boolean={ head.next == null } //修改节点信息 def update(heroNode: HeroNode):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) } } //删除一个节点 def delete(no:Int):Unit={ if (isEmpty()){ println("链表为空~") return } //让temp指向head var temp =head var flag = false //遍历,让temp指向,要删除的节点的前一个节点 breakable { while (true) { if (temp.next.no == no) { flag = true break() } //判断temp是否指向链表的倒数第二个节点 if (temp.next.next == null){ break() } temp = temp.next } } //判断flag if (flag){ //找到了 temp.next = temp.next.next }else{ printf("要删除的节点%d 不存在",no) } } } class HeroNode(hNO:Int,hName:String,hNickname:String){ val no = hNO var name = hName var nickname = hNickname var next: HeroNode =null }
标签:let pre 输出 flag 编号 标识 定义 unit bool
原文地址:https://www.cnblogs.com/help-silence/p/12919769.html