ruby 在LinkedList上实现了insert_before / after
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 在LinkedList上实现了insert_before / after相关的知识,希望对你有一定的参考价值。
require 'pp'
class LinkedList
attr_accessor :head
def initialize(head=nil)
@head = head
end
def add_to_head(node)
pp "add to head"
node.nxt = @head
@head = node
end
def add_to_tail(node)
runner = @head
while(runner.nxt)
pp "runner #{runner} #{runner.nxt}"
runner = runner.nxt
end
runner.nxt = node
end
def traverse
runner = @head
while(runner)
pp "runner:#{runner} val:#{runner.val} nxt=#{runner.nxt}"
runner = runner.nxt
end
end
def delete_by_value(value)
runner = @head
count = 0
while(runner)
if runner.nxt && runner.nxt.val == value
pp "delete #{runner.nxt}:#{runner.nxt.val}"
runner.nxt = runner.nxt.nxt
count += 1
end
runner = runner.nxt
end
count
end
def insert_after(node, value)
runner = @head
while(runner)
break if runner.nil?
if runner.val == value
node.nxt = runner.nxt
runner.nxt = node
end
runner = runner.nxt
end
self
end
def insert_before(node, value)
runner = @head
while(runner)
break if runner.nil? || runner.nxt.nil?
if runner.nxt.val == value
node.nxt = runner.nxt
runner.nxt = node
runner = node
end
runner = runner.nxt
end
self
end
end
class Node
attr_accessor :val, :nxt
def initialize(val="")
@val = val
@nxt = nil
end
end
以上是关于ruby 在LinkedList上实现了insert_before / after的主要内容,如果未能解决你的问题,请参考以下文章
云享·人物开发者故事:从智慧园区智慧金融到智能制造,我们在华为云上实现了降本增效
轻松两步,我在 SpringBoot 服务上实现了接口限流
轻松两步,我在 SpringBoot 服务上实现了接口限流
菜鸟贴;在DE1-S0C上实现了一个FPGA的自动售货机
ruby Ruby的算法和数据结构 - #7 LinkedList
在 Android 上实现推送通知的简单方法