添加 203.移除链表元素 Ruby 版本

This commit is contained in:
Kuxry
2024-10-22 11:46:28 +09:00
parent 12f72eac1e
commit ad93277357

View File

@ -737,7 +737,45 @@ public class Solution
}
}
```
### Ruby#
```ruby
# 定义链表节点
class ListNode
attr_accessor :val, :next
def initialize(val = 0, _next = nil)
@val = val
@next = _next
end
end
# 删除链表中值为 val 的节点
def remove_elements(head, val)
# 创建一个虚拟头节点,这样可以简化删除头节点的处理
# 虚拟头节点的值为 0指向当前链表的头节点
dummy = ListNode.new(0)
dummy.next = head
# 初始化当前节点为虚拟头节点
current = dummy
# 遍历链表,直到当前节点的下一个节点为空
while current.next
# 如果当前节点的下一个节点的值等于 val
if current.next.val == val
# 跳过该节点,即将当前节点的 next 指向下一个节点的 next
current.next = current.next.next
else
# 否则继续遍历,当前节点向前移动
current = current.next
end
end
# 返回删除 val 后的新链表的头节点,虚拟头节点的 next 就是新的头节点
dummy.next
end
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">