forked from mohitjain/leetcode_solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path206_reverse_a_linked_list.rb
More file actions
63 lines (61 loc) · 1.45 KB
/
206_reverse_a_linked_list.rb
File metadata and controls
63 lines (61 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# Leetcode Problem: https://leetcode.com/problems/reverse-linked-list/
#Reverse a singly linked list.
#
# Example:
#
# Input: 1->2->3->4->5->NULL
# Output: 5->4->3->2->1->NULL
#
# Follow up:
#
# A linked list can be reversed either iteratively or recursively. Could you implement both?
#
#-----------------------------------------------------------------------------------------------------------------------
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val = 0, _next = nil)
# @val = val
# @next = _next
# end
# end
# @param {ListNode} head
# @return {ListNode}
#
# --------------------------- USING STACK ------------------------------------------------------------------------------
# require_relative 'core/linked_list'
# require_relative 'core/stack'
# def reverse_list(head)
# stack = Stack.new
# until head.nil?
# stack.push head
# head = head.next
# end
#
# head = nil
# current = nil
# until stack.empty?
# node = stack.pop
# if head.nil?
# head = node
# current = node
# else
# current.next = node
# current = current.next
# end
# end
# head
# end
def reverse_list(head)
current = head
previous = nil
until current.nil?
next_element = current.next
current.next = previous
previous = current
current = next_element
end
previous
end
list = LinkedList.new([1, 2, 3, 4, 5])
p reverse_list(list.head)