添加0206.翻转链表 Kotlin解析版

This commit is contained in:
Ezralin
2022-07-11 15:09:41 +08:00
parent 3ac62c60aa
commit e0a4228599

View File

@ -420,6 +420,41 @@ fun reverseList(head: ListNode?): ListNode? {
return pre
}
```
```kotlin
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun reverseList(head: ListNode?): ListNode? {
// temp用来存储临时的节点
var temp: ListNode?
// cur用来遍历链表
var cur: ListNode? = head
// pre用来作为链表反转的工具
// pre是比pre前一位的节点
var pre: ListNode? = null
while (cur != null) {
// 临时存储原本cur的下一个节点
temp = cur.next
// 使cur下一节点地址为它之前的
cur.next = pre
// 之后随着cur的遍历移动pre
pre = cur;
// 移动cur遍历链表各个节点
cur = temp;
}
// 由于开头使用pre为null,所以cur等于链表本身长度+1
// 此时pre在cur前一位所以此时pre为头节点
return pre;
}
}
```
Swift
```swift