Skip to content

Commit ad93277

Browse files
committed
添加 203.移除链表元素 Ruby 版本
1 parent 12f72ea commit ad93277

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

problems/0203.移除链表元素.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -737,7 +737,45 @@ public class Solution
737737
}
738738
}
739739
```
740+
### Ruby#
741+
742+
```ruby
743+
# 定义链表节点
744+
class ListNode
745+
attr_accessor :val, :next
746+
def initialize(val = 0, _next = nil)
747+
@val = val
748+
@next = _next
749+
end
750+
end
751+
752+
# 删除链表中值为 val 的节点
753+
def remove_elements(head, val)
754+
# 创建一个虚拟头节点,这样可以简化删除头节点的处理
755+
# 虚拟头节点的值为 0,指向当前链表的头节点
756+
dummy = ListNode.new(0)
757+
dummy.next = head
758+
759+
# 初始化当前节点为虚拟头节点
760+
current = dummy
761+
762+
# 遍历链表,直到当前节点的下一个节点为空
763+
while current.next
764+
# 如果当前节点的下一个节点的值等于 val
765+
if current.next.val == val
766+
# 跳过该节点,即将当前节点的 next 指向下一个节点的 next
767+
current.next = current.next.next
768+
else
769+
# 否则继续遍历,当前节点向前移动
770+
current = current.next
771+
end
772+
end
773+
774+
# 返回删除 val 后的新链表的头节点,虚拟头节点的 next 就是新的头节点
775+
dummy.next
776+
end
740777

778+
```
741779

742780
<p align="center">
743781
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
 (0)