overridefunpush(e: E){val newNode =Node(null, e)if(head !=null){// val lastNode = node(len - 1)//O(1)时间复杂度
last?.next = newNode
}else{
head = newNode
}
last = newNode
len++}
4.size(): Int,返回链表的长度
overridefunsize(): Int {return len
}
5.getValue(index: Int): E?,获取列表的value值
overridefungetValue(index: Int): E?{if(index <0|| index >= len){throwArrayIndexOutOfBoundsException("数组越界.....")}returnnode(index)?.value
}//找到对应index下标的节点。privatefunnode(index: Int): Node<E>?{var h = head
//O(n)时间复杂度for(i in0 until index){
h = h?.next
}return h
}
6.insert(index: Int,e: E),从任意位置插入一个节点
overridefuninsert(index: Int, e: E){val newNode =Node(null, e)//考虑边界if(index ==0){val h = head
head = newNode
newNode.next = h
}else{//考虑最后一个位置val prev =node(index -1)val next = prev?.next
prev?.next = newNode
newNode.next = next
}
len++}//找到对应index下标的节点。privatefunnode(index: Int): Node<E>?{var h = head
//O(n)时间复杂度for(i in0 until index){
h = h?.next
}return h
}
7.remove(index: Int),任意位置删除一个节点
overridefunremove(index: Int){if(index <0|| index >= len){throwArrayIndexOutOfBoundsException("数组越界.....")}if(index ==0){val h = head
head = h?.next
h?.next =null}else{val prev =node(index -1)val current = prev?.next
prev?.next = current?.next
current?.next =null}
len--}//找到对应index下标的节点。privatefunnode(index: Int): Node<E>?{var h = head
//O(n)时间复杂度for(i in0 until index){
h = h?.next
}return h
}
8.完整Demo
package day1
class LinkedList<E>: LinkedListAction<E>{//头指针privatevar head: Node<E>?=null//优化时间复杂度privatevar last: Node<E>?=null//集合的长度privatevar len =0overridefunpush(e: E){val newNode =Node(null, e)if(head !=null){// val lastNode = node(len - 1)//O(1)时间复杂度
last?.next = newNode
}else{
head = newNode
}
last = newNode
len++}//找到对应index下标的节点。privatefunnode(index: Int): Node<E>?{var h = head
//O(n)时间复杂度for(i in0 until index){
h = h?.next
}return h
}overridefunsize(): Int {return len
}overridefungetValue(index: Int): E?{if(index <0|| index >= len){throwArrayIndexOutOfBoundsException("数组越界.....")}returnnode(index)?.value
}overridefuninsert(index: Int, e: E){val newNode =Node(null, e)//考虑边界if(index ==0){val h = head
head = newNode
newNode.next = h
}else{//考虑最后一个位置val prev =node(index -1)val next = prev?.next
prev?.next = newNode
newNode.next = next
}
len++}overridefunremove(index: Int){if(index <0|| index >= len){throwArrayIndexOutOfBoundsException("数组越界.....")}if(index ==0){val h = head
head = h?.next
h?.next =null}else{val prev =node(index -1)val current = prev?.next
prev?.next = current?.next
current?.next =null}
len--}}