添加 0206.翻转链表.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-11 23:03:42 +08:00
parent 898016b8a9
commit 3606a62423

View File

@ -496,6 +496,40 @@ struct ListNode* reverseList(struct ListNode* head){
return reverse(NULL, head);
}
```
Scala:
双指针法:
```scala
object Solution {
def reverseList(head: ListNode): ListNode = {
var pre: ListNode = null
var cur = head
while (cur != null) {
var tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
}
pre
}
}
```
递归法:
```scala
object Solution {
def reverseList(head: ListNode): ListNode = {
reverse(null, head)
}
def reverse(pre: ListNode, cur: ListNode): ListNode = {
if (cur == null) {
return pre // 如果当前cur为空则返回pre
}
val tmp: ListNode = cur.next
cur.next = pre
reverse(cur, tmp) // 此时cur成为前一个节点tmp是当前节点
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>