- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0148-sort-list.rb
33 lines (31 loc) · 694 Bytes
/
0148-sort-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
# frozen_string_literal: true
# 148. Sort List
# https://leetcode.com/problems/sort-list
# Medium
# 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}
defsort_list(head)
returnnilifhead.nil?
array=[]
tmp=head
whiletmp
array.push(tmp)
tmp=tmp.next
end
# As a rule against bugs.
# Take list node - nil pointers.
array.each{ |x| x.next=nil}
array.sort!{ |a,b| a.val <=> b.val}
(0...(array.size - 1)).eachdo |i|
array[i].next=array[i + 1]
end
array[0]
end