问题
I want to sort doubly linked list by next_id
value.
My DLL:
const dll = [
{id: '22', prev_id: '41', next_id: '45'},
{id: '45', prev_id: '22', next_id: null},
{id: '41', prev_id: '14', next_id: '22'},
{id: '14', prev_id: null, next_id: '41'},
]
As a result:
const dll_result = [
{id: '14', prev_id: null, next_id: '41'}, // next item - 41
{id: '41', prev_id: '14', next_id: '22'}, // next item - 22
{id: '22', prev_id: '41', next_id: '45'}, // next item - 45
{id: '45', prev_id: '22', next_id: null},
]
I understand that it may not make sense to sort the DLL, but in my case I need to sequentially visualize the data from the array using next_id
.
P.S. It would be nice to know even a native solution, and then I could try to convert to Ramda.js myself
回答1:
Create am index of items by id
, find the 1st item (prev_id
=== null), and then iterate with a while loop, and push the current object into the result array:
const findStart = R.find(R.propEq('prev_id', null))
const indexById = R.indexBy(R.prop('id'))
const sortByNextId = arr => {
const index = indexById(arr)
let current = findStart(arr)
const sorted = []
while(current) {
sorted.push(current)
current = index[current.next_id]
}
return sorted
}
const dll = [
{id: '22', prev_id: '41', next_id: '45'},
{id: '45', prev_id: '22', next_id: null},
{id: '41', prev_id: '14', next_id: '22'},
{id: '14', prev_id: null, next_id: '41'},
]
const result = sortByNextId(dll)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
回答2:
Native approach
You can sort by id
and pick the lowest id
as the first element of the desired output, then you can push the next elements by finding the next node using the attribute next_id
.
const dll = [{id: '22', prev_id: '41', next_id: '45'},{id: '45', prev_id: '22', next_id: null},{id: '41', prev_id: '14', next_id: '22'},{id: '14', prev_id: null, next_id: '41'}],
result = [[...dll].sort((a, b) => a.id - b.id).shift()];
dll.forEach(() => result.push(dll.find(({id}) => id === result[result.length - 1].next_id)));
console.log(result);
来源:https://stackoverflow.com/questions/60297661/sort-doubly-linked-list-by-next-id-ramda-js