Created
March 29, 2020 09:27
-
-
Save eebasadre20/739e7c85a437335322e31fdd3618a408 to your computer and use it in GitHub Desktop.
LeetCode - Reverse Linkedlist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Definition for singly-linked list. | |
# class ListNode | |
# attr_accessor :val, :next | |
# def initialize(val) | |
# @val = val | |
# @next = nil | |
# end | |
# end | |
# @param {ListNode} head | |
# @return {ListNode} | |
def reverse_list(head) | |
node_length = list_node_length(head) | |
counter = 0 | |
while counter_x < node_length | |
swap_list(head, node_length - 1, counter) | |
counter_x += 1 | |
end | |
head | |
end | |
def swap_list(current_node, node_length, count) | |
return current_node if node_length == count | |
if !current_node.next.nil? | |
temp_val = current_node.val | |
current_node.val = current_node.next.val | |
current_node.next.val = temp_val | |
count += 1 | |
swap_list(current_node.next, node_length, count) | |
end | |
end | |
def linkedlist_length(head, count = 0) | |
return count if head.nil? | |
count += 1 | |
list_node_length(head.next, count) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment