Re-ordering a Linked List in Python

后端 未结 2 1996
暖寄归人
暖寄归人 2021-01-28 13:54

I realize this sort of data structure is better done with built in list type, but I\'m trying to understand this more for academic reasons. Given that I have a linked list like

2条回答
  •  萌比男神i
    2021-01-28 14:18

    Sometimes the best thing is to first think "how fast would an optimal solution be?" This seems pretty apparently O(length), so something that runs through the list, preferably once, is going to be about as good as you can do.

    Given that, you're probably going to find the simplest choice is best. In pseudocode, it would be

     get the first element in left
     get the second element in right
     append them to a new list as right->left
     repeat until you run out of list.
    

    As Matt and Jodaka note, you do need to decide what to do with an odd-length list, if an odd-length list is permitted at all.

提交回复
热议问题