mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0206.翻转链表.md Scala版本
This commit is contained in:
@ -496,6 +496,40 @@ struct ListNode* reverseList(struct ListNode* head){
|
|||||||
return reverse(NULL, 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>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user