From ef8564a5930805ace91776c5648fa7110800c2d7 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Wed, 11 May 2022 19:51:07 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200203.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0.md=20Scala=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0203.移除链表元素.md | 32 ++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index c34831b7..53230c0b 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -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 + } +} +``` -----------------------