Last active
July 14, 2022 10:25
-
-
Save Hasiy/f2f1282e1e630b18c0c4a7a81d0eb493 to your computer and use it in GitHub Desktop.
Kotlin ListNode链表
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com | |
/* | |
* @Author: Hasiy | |
* @Date: 2020/4/1 - 16 : 47 | |
* @Description: institute-Android | |
* @Email: Zhuxs@venpoo.com | |
*/ | |
class ListNode<T>(val value: T) { | |
var next: ListNode<T>? = null | |
override fun toString(): String { | |
return "$value -> ${next?.value ?: "null"}" | |
} | |
} | |
fun <T> ListNode<T>?.toList(): List<T> { | |
this?.let { | |
val list = ArrayList<T>() | |
var tempNode: ListNode<T>? = this | |
while (tempNode != null) { | |
list += tempNode.value | |
tempNode = tempNode.next | |
} | |
return list | |
} ?: return emptyList() | |
} | |
//单向链表 | |
class LinkedNode<T>(var value: T) { | |
var next: LinkedNode<T>? = null //指向下一个存储节点的next指针 | |
} | |
//双向链表 | |
class DoubleLinkedNode<T>(var value: T) { | |
var prev: DoubleLinkedNode<T>? = null //指向上一个存储节点的prev指针 | |
var next: DoubleLinkedNode<T>? = null //指向下一个存储节点的next指针 | |
} | |
//栈 | |
class LinkedStack { | |
private var first: Node? = null | |
private var len: Int = 0 | |
fun push(value: Int) {//相当于链表从表头插入新的元素 | |
val oldFirst = first | |
first = Node(value) | |
first?.next = oldFirst | |
len++ | |
} | |
fun pop(): Int {//相当于链表从表头删除新的元素 | |
val value = first?.value | |
first = first?.next | |
return value ?: -1 | |
} | |
fun top(): Int { | |
return first?.value ?: -1 | |
} | |
fun isEmpty(): Boolean { | |
return first == null | |
} | |
fun size(): Int { | |
return len | |
} | |
inner class Node(var value: Int) { | |
var next: Node? = null | |
} | |
} | |
//队列 | |
class LinkedQueue { | |
private var first: Node? = null | |
private var last: Node? = null | |
private var len: Int = 0 | |
fun enqueue(value: Int) {//相当于链表从尾部插入新的节点 | |
val oldLast = last | |
last = Node(value) | |
last?.next = null | |
if (isEmpty()) { | |
first = last | |
} else { | |
oldLast?.next = last | |
} | |
len++ | |
} | |
fun dequeue(): Int {//相当于链表从尾部删除最后节点 | |
val value = first?.value ?: -1 | |
first = first?.next | |
if (isEmpty()) { | |
last = null | |
} | |
return value | |
} | |
fun isEmpty(): Boolean { | |
return first == null | |
} | |
fun size(): Int { | |
return len | |
} | |
inner class Node(var value: Int) { | |
var next: Node? = null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment