From e0a422859904ddae865cc828bc30d6620ccb8137 Mon Sep 17 00:00:00 2001 From: Ezralin <10881430+ezralin@user.noreply.gitee.com> Date: Mon, 11 Jul 2022 15:09:41 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00206.=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=20Kotlin=E8=A7=A3=E6=9E=90=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0206.翻转链表.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md index 24ec7b94..bb9b62d5 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -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