-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.rb
More file actions
65 lines (41 loc) · 975 Bytes
/
Solution.rb
File metadata and controls
65 lines (41 loc) · 975 Bytes
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
# 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 swap_pairs(head)
if head.nil? or head.next.nil?
return head
end
second_node = head
head = head.next
third_node = head.next
head.next = second_node
second_node.next = (third_node.nil? or third_node.next.nil?) ? third_node : third_node.next
until third_node.nil? do
ptr = third_node
second_node = ptr.next
if second_node.nil?
return head
end
third_node = second_node.next
second_node.next = ptr
ptr.next = (third_node.nil? or third_node.next.nil?) ? third_node : third_node.next
end
head
end
head = ListNode.new 1
head.next = ListNode.new 2
head.next.next = ListNode.new 3
head.next.next.next = ListNode.new 4
head = swap_pairs head
ptr = head
until ptr.nil?
print "#{ptr.val}->"
ptr = ptr.next
end