题解 | #合并k个已排序的链表#

合并k个已排序的链表

http://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

/**

  • Definition for singly-linked list.

  • struct ListNode {

  • int val;
    
  • ListNode *next;
    
  • ListNode(int x) : val(x), next(NULL) {}
    
  • }; */ class Solution { public: ListNode *mergeTwoList(ListNode *l1,ListNode *l2){ ListNode *l3=new ListNode(0); ListNode *cur=l3; while(l1!=nullptr && l2!=nullptr){ if(l1->val<=l2->val){ cur->next=l1; l1=l1->next; }else{ cur->next=l2; l2=l2->next;
    }
    cur=cur->next; } if(l1!=nullptr){ cur->next=l1; }else{ cur->next=l2; } return l3->next; }

    ListNode *mergeKLists(vector<ListNode *> &lists) { int n=lists.size(); if(n==1){ return lists[0]; }else if(n==0){ return nullptr; }else{ ListNode *l1=lists[0]; ListNode *l2=nullptr; for(int i=1;i<n;i++){ l2=lists[i]; l1=mergeTwoList(l1,l2); } return l1; } } };

全部评论

相关推荐

06-11 17:39
门头沟学院 Java
小呆呆的大鼻涕:卧槽,用户彻底怒了
点赞 评论 收藏
分享
06-07 12:20
新余学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务