-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathpalindrome_linked_list.rb
85 lines (69 loc) · 1.49 KB
/
palindrome_linked_list.rb
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# Refactor/rewrite this file
class Node
attr_accessor :value, :next
def initialize(val, next_in_line)
@value = val
@next = next_in_line
end
end
class LinkedList
attr_accessor :head
def initialize(val)
@head = Node.new(val, nil)
end
def add(value)
# Traverse to the end of the list
# And insert a new node over there with the specified value
current = @head
current = current.next until current.next.nil?
current.next = Node.new(value, nil)
self
end
def delete(val)
current = @head
if current.value == val
@head = @head.next
else
until current.next.nil?
current = current.next
if current.value == val
current.value = current.next.value || nil
current.next = current.next.next
end
end
end
@head
end
end
def list_palindrome(list)
stack = []
current = list.head
while current
stack.push(current.value)
current = current.next
end
current = list.head
while current
stack_temp = stack.pop
return false unless current.value == stack_temp
current = current.next
end
true
end
def list_check(list)
return false unless list
stack = []
slow = fast = list.head
while fast && !fast.next.nil?
fast = fast.next.next
stack.push(slow.value)
slow = slow.next
end
slow = slow.next unless fast.nil?
until slow.nil?
temp = stack.pop
return false unless slow.value == temp
slow = slow.next
end
true
end