如何在Ruby中实现链表的#pop

nkhmeac6  于 2023-04-20  发布在  Ruby
关注(0)|答案(1)|浏览(108)

我一直在努力寻找一个在Ruby的LinkedList结构中实现#pop的解决方案,目前我的实现已经到了删除最后一个元素的地步(通过在倒数第二个节点上将@next_node元素设置为nil)并返回新的最后一个元素,但我需要我的方法记住并返回我循环过的所有以前的节点,我正在努力寻找一种方法来做到这一点。有人能帮助我吗:
LinkedList示例结构;

"#<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
pb3skfrl

pb3skfrl1#

下面是更新后的代码,其中包含一些注解,以回顾您所做的工作:

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.返回的是倒数第二个节点,而不是最后一个节点。
1.如果链表只包含1个节点,则代码将失败。
我将专注于修正(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

相关问题