单链表反转两种方法
2020-10-28 本文已影响0人
郑永博
https://www.cnblogs.com/mwl523/p/10749144.html
package com.example.myapplication
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
var message = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var A = Node("A")
var B = Node("B")
var C = Node("C")
var D = Node("D")
A.next = B
B.next = C
C.next = D
D.next = null
printNode(A)
Log.e("ssssss", message)
message = ""
var newNode = reverseNode(A)
printNode(newNode)
Log.e("ssssss", message)
}
private fun reverseNode(a: Node?): Node? {
var preNode: Node? = null
var nextNode: Node? = null
var curNode: Node? = a
while (curNode != null) {
nextNode = curNode.next
curNode.next = preNode
preNode = curNode
curNode = nextNode
}
return preNode
}
private fun printNode(a: Node?) {
if (a == null) {
return
}
if (a.next != null) {
message += (a.name + "->")
printNode(a.next)
} else {
message += (a.name + "-> NULL")
}
}
}
import java.util.*
fun main() {
val listNode = ListNode(1)
val listNode2 = ListNode(2)
val listNode3 = ListNode(3)
val listNode4 = ListNode(4)
listNode.next = listNode2
listNode2.next = listNode3
listNode3.next = listNode4
listNode4.next = null
val result = reverseListNode(listNode)
print(result.toString())
}
private fun reverseListNode(listNode: ListNode): ListNode {
var temp: ListNode? = listNode
var result = ListNode(-1)
while (temp != null) {
var pNext = temp.next
temp.next = result.next
result.next = temp
temp = pNext
}
return result.next!!
}
class ListNode(var value: Int) {
var next: ListNode? = null
var hasNext: Boolean = (next != null)
override fun toString(): String {
val stack: Stack<Int> = Stack()
var temp: ListNode? = this
while (temp != null) {
stack.push(temp.value)
temp = temp.next
}
val arraylist: ArrayList<Int> = ArrayList()
while (!stack.isEmpty()){
arraylist.add(stack.pop())
}
arraylist.reverse()
return arraylist.toString()
}
}