赞
踩
interface LinkedListAction<E> {
fun push(e: E)
fun size(): Int
fun getValue(index: Int): E?
fun insert(index: Int,e: E)
fun remove(index: Int)
}
data class Node<E>(var next: Node<E>? = null, var value: E)
override fun push(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++
}
override fun size(): Int {
return len
}
override fun getValue(index: Int): E? {
if (index < 0 || index >= len) {
throw ArrayIndexOutOfBoundsException("数组越界.....")
}
return node(index)?.value
}
//找到对应index下标的节点。
private fun node(index: Int): Node<E>? {
var h = head
//O(n)时间复杂度
for (i in 0 until index) {
h = h?.next
}
return h
}
override fun insert(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下标的节点。 private fun node(index: Int): Node<E>? { var h = head //O(n)时间复杂度 for (i in 0 until index) { h = h?.next } return h }
override fun remove(index: Int) { if (index < 0 || index >= len) { throw ArrayIndexOutOfBoundsException("数组越界.....") } 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下标的节点。 private fun node(index: Int): Node<E>? { var h = head //O(n)时间复杂度 for (i in 0 until index) { h = h?.next } return h }
package day1 class LinkedList<E> : LinkedListAction<E> { //头指针 private var head: Node<E>? = null //优化时间复杂度 private var last: Node<E>? = null //集合的长度 private var len = 0 override fun push(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下标的节点。 private fun node(index: Int): Node<E>? { var h = head //O(n)时间复杂度 for (i in 0 until index) { h = h?.next } return h } override fun size(): Int { return len } override fun getValue(index: Int): E? { if (index < 0 || index >= len) { throw ArrayIndexOutOfBoundsException("数组越界.....") } return node(index)?.value } override fun insert(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++ } override fun remove(index: Int) { if (index < 0 || index >= len) { throw ArrayIndexOutOfBoundsException("数组越界.....") } 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-- } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。