添加 0203.移除链表元素.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-11 19:51:07 +08:00
parent 558dc33431
commit ef8564a593

View File

@ -446,6 +446,36 @@ impl Solution {
}
}
```
Scala:
```scala
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def removeElements(head: ListNode, `val`: Int): ListNode = {
if (head == null) return head
var dummy = new ListNode(-1, head) // 定义虚拟头节点
var cur = head // cur 表示当前节点
var pre = dummy // pre 表示cur前一个节点
while (cur != null) {
if (cur.x == `val`) {
// 相等就删除那么cur的前一个节点pre执行cur的下一个
pre.next = cur.next
} else {
// 不相等pre就等于当前cur节点
pre = cur
}
// 向下迭代
cur = cur.next
}
// 最终返回dummy的下一个就是链表的头
dummy.next
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>