class StuNode(val pno:Int,val pname:String){
val no:Int=pno
var name: String = pname
var next:StuNode=null //下节点,默认null
}
/**
* 说明:只是demo用于理解,有很多漏洞,具体根据应用场景解决
*/
class SingleLinkList{
//头节点
val head:StuNode=new StuNode(0,null)
//无顺序添加节点
def add(stuNode:StuNode):Unit={
var tmp=head
breakable{
while(true){
if(tmp.next==null){
break()
}
tmp=tmp.next
}
}
//此时tmp就是尾节点
tmp.next=stuNode
}
//遍历
def list():Unit={
if(head.next==null){
print("this linkList is empty!")
return
}
//tmp就是要遍历的节点
var tmp=head.next
breakable {
while (true) {
if (tmp == null) break()
printf("no:%d\tname:%s\n", tmp.no, tmp.name)
tmp = tmp.next
}
}
}
//更新节点
def modify(stuNode:StuNode):Unit={
if(head.next==null){
print("this linkList is empty!")
return
}
var tmp=head.next
var flag:Boolean=false//标志是否找到目标节点
breakable {
while (true) {
if (tmp == null) break()
if (tmp.no == stuNode.no) { //找到目标节点
flag=true
break()
}
tmp = tmp.next
}
}
if(flag){
//此时tmp就是目标节点
tmp.name=stuNode.name
}else{
println("the target node is not exits!")
}
}
//删除节点
def del(stuNode:StuNode):Unit={
if(head.next==null){
print("this linkList is empty!")
return
}
var tmp=head
var flag=false//标志是否找到目标节点
breakable {
while (true) {
//确定是否有下个节点
if (tmp.next == null) break()
if (tmp.next.no == stuNode.no) { //当前节点的下一个节点是否就是目标节点
flag = true
break()
}
tmp = tmp.next
}
}
if(flag){
//此时tmp的next节点就是目标节点
tmp.next=tmp.next.next
}else{
println("the target node is not exits!")
}
}
//按照no顺序添加
def addOrderByNo(stuNode:StuNode):Unit={
var tmp=head
breakable {
while (true) {
if (tmp.next == null) {
break()
}
if (tmp.next.no > stuNode.no) {
break()
}
tmp = tmp.next
}
}
//此时tmp的next就是要添加的位置
stuNode.next=tmp.next
tmp.next=stuNode
}
/*
//无顺序添加节点
def add(stuNode:StuNode):Unit={
var tmp=head
breakable{
while(true){
if(tmp.next==null){
break()
}
tmp=tmp.next
}
}
//此时tmp就是尾节点
//处理重复添加问题,避免死循环
val tmpNode:StuNode=new StuNode(stuNode.no,stuNode.name)
tmp.next=tmpNode
}
//更新节点
def modify(stuNode:StuNode):Unit={
if(head.next==null){
print("this linkList is empty!")
return
}
var tmp=head.next
var flag:Boolean=false//标志是否找到目标节点
breakable {
while (true) {
if (tmp == null) break()
if (tmp.no == stuNode.no) { //找到目标节点
//此时tmp就是目标节点
tmp.name=stuNode.name
}
tmp = tmp.next
}
}
if(flag){
println("the target node is not exits!")
}
}
*/
}