C++ 排序链表的合并-a

已知两个已排序链表头节点指针l1与l2,将这两个链表合并,合并后认为有序的,返回合并后的头节点。
思路:
比较l1和l2指向的节点,将较小的节点插入到pre指针后,并向前移动较小节点对应的指针。

#include <stdio.h>
#include <vector>
#include<algorithm>
#include<typeinfo>
struct ListNode
{
 int val;
 ListNode* next;
 ListNode(int x) : val(x), next(NULL) {}
};
bool cmp(const ListNode* a, const ListNode* b)
{
 return a->val < b->val;
}
class Solution
{
public:
 Solution() {}
 ~Solution() {}
 //方法一:排序。
 ListNode* mergeKLists(std::vector<ListNode*>& lists)
 {
  std::vector<ListNode*> node_vec;
  for (unsigned int i = 0; i< lists.size(); i++)
  {
   ListNode* head = lists[i];
   while (head)
   {
    node_vec.push_back(head);
    head = head->next;
   }
  }
  if (node_vec.size() ==0)
  {
   return NULL;
  }
  std::sort(node_vec.begin(), node_vec.end(), cmp);
  for (unsigned int j = 1; j< node_vec.size(); j++)
  {
   node_vec[j - 1]->next = node_vec[j];
  }
  node_vec[node_vec.size() - 1]->next = NULL;
  return node_vec[0];
 }
 /*方法二:分治处理。
 对K个链表进行分治,两两进行合并。
 设有k个链表,平均每个链表有n个节点,时间复杂度:
 第1轮,进行k/2次,每次处理2n个数字;
 第2轮,进行k/4次,每次处理4n个数字;
 ……
 最后一轮,进行k/(2^(logk))次,每次处理(2^(logk))n个数字,此处的log以2为底。
 总的时间复杂度为O(kNlogk)。
 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)      //l1和l2为链表或链表节点的首地址
 {
  ListNode temp_head(0);
  ListNode* pre = &temp_head;
  while (l1 && l2)
  {
   if (l1->val < l2->val)
   {
    pre->next = l1;
    l1 = l1->next;
   }
   else
   {
    pre->next = l2;
    l2 = l2->next;
   }
   pre = pre->next;
  }
  if (l1)
  {
   pre->next = l1;
  }
  if (l2)
  {
   pre->next = l2;
  }
  return temp_head.next;
 }
 ListNode* mergeKLists(std::vector<ListNode*> & lists)
  //lists为vector,其中存放的全是链表(或者是链表节点)的首地址ListNode*。
  //lists的各个元素是节点还是链表,取决于该元素第一个节点后面有没有指向其他的节点。
 {
  if (lists.size()==0)
  {
   return NULL;
  }
  if (lists.size()==1)
  {
   return lists[0];         //返回vector中第一个链表或链表节点的首地址
  }
  if (lists.size()==2)
  {
   return mergeTwoLists(lists[0], lists[1]);    //lists[1]为第二个链表或链表节点的首地址
  }
  int mid = lists.size() / 2;
  std::vector<ListNode*> sub1_lists;
  std::vector<ListNode*> sub2_lists;
  for (int i = 0; i < mid; i++)
  {
   sub1_lists.push_back(lists[i]);
  }
  for (int i = mid; i < lists.size(); i++)
  {
   sub2_lists.push_back(lists[i]);
  }
  ListNode* l1 = mergeKLists(sub1_lists);
  ListNode* l2 = mergeKLists(sub2_lists);
  return mergeTwoLists(l1, l2);
 }
 */
};
int main()
{
 ListNode a(1);
 ListNode b(4);
 ListNode c(6);
 ListNode d(0);
 ListNode e(5);
 ListNode f(7);
 ListNode g(2);
 ListNode h(3);
 a.next = &b;
 b.next = &c;
 d.next = &e;
 e.next = &f;
 g.next = &h;
 Solution solve;
 std::vector<ListNode*> lists;
 lists.push_back(&a);
 lists.push_back(&d);
 lists.push_back(&g);
 ListNode* head = solve.mergeKLists(lists);
 while (head)
 {
  printf("%d\n", head->val);
  head = head->next;
 }
 return 0;
}

运行结果:
0
1
2
3
4
5
6
7

发布了61 篇原创文章 · 获赞 47 · 访问量 1610

猜你喜欢

转载自blog.csdn.net/weixin_44208324/article/details/104524647
今日推荐