Home > Mobile >  How to add elements of list of linked list in straight order?
How to add elements of list of linked list in straight order?

Time:03-15

How can I add elements of list of linked list in straight order? For example, I have list of linked list: [[1, 2, 3], [4, 5, 6], [7, 8]] and list new_list and I wanna add all the elements in order 1->2->3->...->7->8 but not in order 1->4->7->2->5->3->6->8. For second case I have code:

new_list = []
        for array in lists:
            while array:
                new_list.append(array.val)
                array = array.next

But how to modify it to get an order as at first case?

CodePudding user response:

Ok so here's what I have simply done:

lists = [[1,2,3],[4,5,6],[7,8]]
new_list = []
for array in lists:
    for i in array:
        new_list.append(i)
print(new_list)
Output: [1,2,3,4,5,6,7,8]

I don't know why you were using array.next or array.val, however I think you can simply get the list and iterate over it's values and then append it without any problem.

CodePudding user response:

If all you want is just concatenating the list use itertools.chain.

Check official docs here.

>>> import itertools
>>> data = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> list(itertools.chain(*data))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

CodePudding user response:

I modify the code and I using pop to get the value and then sort the array, you can try my idea:

lists = [[1, 2, 3], [4, 5, 6], [7, 8]]
new_list = []
for array in lists:
    while array:
        new_list.append(array.pop())
new_list.sort()

So you will get the result which you want : [1, 2, 3, 4, 5, 6, 7, 8]

  • Related