mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
添加 707设计链表 Kotlin实现
This commit is contained in:
@ -880,7 +880,72 @@ MyLinkedList.prototype.deleteAtIndex = function(index) {
|
||||
* obj.deleteAtIndex(index)
|
||||
*/
|
||||
```
|
||||
Kotlin:
|
||||
```kotlin
|
||||
class MyLinkedList {
|
||||
|
||||
var next: ListNode? = null
|
||||
|
||||
var size: Int = 0
|
||||
|
||||
fun get(index: Int): Int {
|
||||
if (index + 1 > size) return -1
|
||||
var cur = this.next
|
||||
for (i in 0 until index) {
|
||||
cur = cur?.next
|
||||
}
|
||||
return cur?.`val` ?: -1
|
||||
}
|
||||
|
||||
fun addAtHead(`val`: Int) {
|
||||
val head = ListNode(`val`)
|
||||
head.next = this.next
|
||||
this.next = head
|
||||
size++
|
||||
}
|
||||
|
||||
fun addAtTail(`val`: Int) {
|
||||
val pre = ListNode(0)
|
||||
pre.next = this.next
|
||||
var cur: ListNode? = pre
|
||||
while (cur?.next != null) {
|
||||
cur = cur.next
|
||||
}
|
||||
cur?.next = ListNode(`val`)
|
||||
this.next = pre.next
|
||||
size++
|
||||
}
|
||||
|
||||
fun addAtIndex(index: Int, `val`: Int) {
|
||||
if (index == 0) return addAtHead(`val`)
|
||||
if (index == size) return addAtTail(`val`)
|
||||
if (index > size) return
|
||||
var cur = this.next
|
||||
for (i in 0 until index - 1) {
|
||||
cur = cur?.next
|
||||
}
|
||||
val temp = cur?.next
|
||||
cur?.next = ListNode(`val`)
|
||||
cur?.next?.next = temp
|
||||
size++
|
||||
}
|
||||
|
||||
fun deleteAtIndex(index: Int) {
|
||||
if (index + 1 > size) return
|
||||
val pre = ListNode(0)
|
||||
pre.next = this.next
|
||||
var cur: ListNode? = pre
|
||||
for (i in 0 until index) {
|
||||
cur = cur?.next
|
||||
}
|
||||
val temp = cur?.next?.next
|
||||
cur?.next?.next = null
|
||||
cur?.next = temp
|
||||
this.next = pre.next
|
||||
size--
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user