在Python中合并两个排序的链表

时间:2018-09-22 05:22:44

标签: python sorting merge linked-list

我正在解决一个Leetcode问题(问题21),该问题接受两个排序的链表并返回一个排序的合并链表。例如,输入:1-> 2-> 4、1-> 3-> 4和输出:1-> 1-> 2-> 3-> 4-> 4。

我对链接列表的经验不是很丰富,但是我试图解决更多的问题以获取更多信息。我的代码没有返回所需的输出[1,1,2,3,4,4],而是返回了[4]。但是,我认为主要的逻辑在那里,希望我能少一些东西。

def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        newList = ListNode(0) # used for single, merged list
        while l1 and l2:
            if l1.val <= l2.val: # compare current node's values
                newList.next = l1
                l1 = l1.next
            else:
                newList.next = l2
                l2 = l2.next

        return newList.next # first node is 0, which we don't want

2 个答案:

答案 0 :(得分:3)

主要逻辑几乎存在,但是每次仅替换列表中的下一个项目(您没有推进列表),因此您仅返回最后一个项目。解决方案是创建另一个用于前进列表的“ cur指针”,同时将newList保留为返回结果的“前指针”。

最后,您还应该与非空列表“保持联系”

def mergeTwoLists(self, l1, l2):
    newList = ListNode(0)
    cur = newList 
    while l1 and l2:
        if l1.val < l2.val:
            cur.next = l1
            l1 = l1.next
        else:
            cur.next = l2
            l2 = l2.next
        cur = cur.next
    cur.next = l1 or l2 # add non-empty list
    return newList.next

答案 1 :(得分:0)

const data = [  {  "id":"5b9ce8d51dbb85944baddfa5","name":"EARBANG","parent_id":0,"status":"Inactive","children":[  {  "id":"5b9ce8d5d978f75e4b1584ba","name":"DIGINETIC","parent_id":"5b9ce8d51dbb85944baddfa5","status":"Active","children":[  {  "id":"5b9ce8d5cb79d63c8b38018c","name":"PREMIANT","parent_id":"5b9ce8d5d978f75e4b1584ba","status":"Active",}]}]},{  "id":"5b9ce8d51650fac75fa359c8","name":"GEEKOLOGY","parent_id":0,"status":"Active",},{  "id":"5b9ce8d59f52e801a2e40a97","name":"TOYLETRY","parent_id":0,"status":"Inactive",},{  "id":"5b9ce8d5d136fcfed2f3e0dd","name":"PAPRIKUT","parent_id":0,"status":"Inactive",},{  "id":"5b9ce8d53afb7a61e188c48e","name":"EYERIS","parent_id":0,"status":"Inactive",}];

// create an array of child ids
function getChildren(obj) {
  return (!Array.isArray(obj)) 
  ? []
  : obj.reduce((arr, curr) => arr.concat(curr.id, ...getChildren(curr.children)), [])
}

// find a particular id
function search(arr, key){
  if (Array.isArray(arr)) { 
    for (obj of arr){
      return (obj.id === key) 
      ? {id: obj.id, childs: getChildren(obj.children)}   // call getChildren once you've found the object
      : search(obj.children, key)
    }
  }
}

console.log(search(data, '5b9ce8d51dbb85944baddfa5'));

// find deeper nesting:
console.log(search(data, '5b9ce8d5d978f75e4b1584ba'));

应该做到这一点。