我正在努力寻找一种在Ruby的LinkedList struct 上实现#POP的解决方案.目前我的实现已经到了删除最后一个元素(将倒数第二个 node 上的@next_node个元素设置为nil)并返回新的最后一个元素的地步,但我需要我的方法来记住并返回我循环过的所有以前的 node ,我正在努力找到一种方法来做到这一点.有谁能帮帮我:

LinkedList示例 struct ;

"#<LinkedList:0x000000010ced2508 @head=#<Node:0x000000010ced22b0 @value=13, @next_node=#<Node:0x000000010ced22d8 @value=2, @next_node=#<Node:0x000000010ced2300 @value=25, @next_node=#<Node:0x000000010ced2328 @value=20, @next_node=nil>>>>>"

我目前的#POP实现:

  def pop
    return if head.nil?
    current_node = head
    current_node = current_node.next_node until current_node.next_node.next_node.nil?
    current_node.next_node = nil
    return current_node
  end

根据@tom-Lord的答复,更新了工作方法:

def pop
    if head.nil?
      return head
    elsif head.next_node.nil?
      self.head = nil
      return head
    else
      second_last_node = head
      second_last_node = second_last_node.next_node until second_last_node.next_node.next_node.nil?
  
      last_node = second_last_node.next_node
      second_last_node.next_node = nil
      return last_node
    end
  end

推荐答案

以下是您的代码更新后的一些注释,以总结您所做的工作:

def pop
  # Handles the edge case where the list is empty -- fine.
  return if head.nil?

  # Sets `current_node` to the **SECOND-LAST** node.
  current_node = head
  current_node = current_node.next_node until current_node.next_node.next_node.nil?

  # Deletes the SECOND-LAST node's pointer
  current_node.next_node = nil
  
  # Returns the SECOND-LAST node (???!!)
  return current_node
end

这里有两件事出了问题:

  1. 您将返回倒数第二个 node ,而不是最后一个 node .
  2. 对于恰好包含1个 node 的链表,您的代码将失败.

我将专注于修复(1),并将(2)作为扩展,让您自己解决.

def pop
  # Handles the edge case where the list is empty -- fine.
  return if head.nil?

  # Using a more descriptive variable name makes it clearer what's happening
  second_last_node = head
  second_last_node = second_last_node.next_node until second_last_node.next_node.next_node.nil?

  last_node = second_last_node.next_node
  second_last_node.next_node = nil
  
  return last_node
end

Ruby相关问答推荐

这是一个很好的测试?规范

在 ruby​​ 中提取文档中的主题标签和部分

Ruby中带和不带下划线_的方法参数有什么区别

有没有办法在 Capybara 中保持登录状态?

拆分 Ruby 字符串时如何保留分隔符?

在 YAML 变量中包含 jekyll / liquid 模板数据?

进程的 pid、ppid、uid、euid、gid 和 egid 有什么区别?

Ruby字符串上的扫描和匹配有什么区别

YAML 每个缩进多少个空格?

如何获取从位置 N 到 Ruby 中最后一个字符的子字符串?

Ruby 中的 method_missing trap

从 1 开始循环

对于基于 GitHub 的 gem,强制Bundle 安装使用 https:// 而不是 git://

将Elastic search限制设置为无限制

我安装了一个 gem,但 require 'gemname' 不起作用.为什么?

如何在 Ruby 中获取堆栈跟踪对象?

获取Ruby中当前目录的父目录

何时使用在 Ruby 中启动子进程的每种方法

相当于 Ruby 的 cURL?

如何将逗号分隔的字符串转换为数组?