Help us understand the problem. What is going on with this article?

Leetcode: Reverse Linked List

require 'minitest/autorun'
require 'pry'
class ReverseLinkedList < Minitest::Test

  def test_run
    # Input: 1->2->3->4->5->NULL
    # Output: 5->4->3->2->1->NULL
    head = ListNode.new(1)
    head.next = ListNode.new(2)
    head.next.next = ListNode.new(3)
    head.next.next.next = ListNode.new(4)
    head.next.next.next.next = ListNode.new(5)
    new_head = reverse_list(head)
    assert_equal(5, new_head.val)
    assert_equal(4, new_head.next.val)
    assert_equal(3, new_head.next.next.val)
    assert_equal(2, new_head.next.next.next.val)
    assert_equal(1, new_head.next.next.next.next.val)
    assert_equal(nil, new_head.next.next.next.next.next)
  end

  def reverse_list(head)
    return head if head.nil? || head.next.nil?

    p = head
    q = p.next
    q = reverse_list(q)

    # qはp.nextなので、p.next.next = p は q.next = pと同じ。なので、この行でq.nextが決まる。
    p.next.next = p
    p.next = nil
    q
  end

end

class ListNode
  attr_accessor :val, :next

  def initialize(val)
    @val = val
    @next = nil
  end

end
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした