Chinaunix首页 | 论坛 | 博客
  • 博客访问: 100989
  • 博文数量: 35
  • 博客积分: 28
  • 博客等级: 民兵
  • 技术积分: 136
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-03 16:08
文章分类
文章存档

2014年(2)

2013年(9)

2012年(24)

分类:

2012-07-27 17:38:02

原文地址:合并链表排序 作者:xiwrong

 

  1. #include "stdafx.h"
  2. #include "stdlib.h"

  3. #ifdef _DEBUG
  4. #define new DEBUG_NEW
  5. #endif



  6. typedef struct _node
  7. {
  8.  int date;
  9.  struct _node* next;
  10. } Node, *NodeList;

  11. NodeList creat_list_1()
  12. {
  13.  NodeList head, pCurr, pPrev;
  14.  head = (NodeList)malloc(sizeof(Node));
  15.  pPrev = head;
  16.  for (int i = 0; i < 3; i++)
  17.  {
  18.   pCurr = (NodeList)malloc(sizeof(Node));
  19.   pCurr->date = 2*i + 3;
  20.   pPrev->next = pCurr;
  21.   pPrev = pCurr;
  22.  }
  23.  pCurr->next = NULL;

  24.  return head;
  25. }
  26. NodeList creat_list_2()
  27. {
  28.  NodeList head, pCurr, pPrev;
  29.  head = (NodeList)malloc(sizeof(Node));
  30.  pPrev = head;
  31.  for (int i = 0; i < 3; i++)
  32.  {
  33.   pCurr = (NodeList)malloc(sizeof(Node));
  34.   pCurr->date = 2*i + 2;
  35.   pPrev->next = pCurr;
  36.   pPrev = pCurr;
  37.  }
  38.  pCurr->next = NULL;

  39.  return head;
  40. }

  41. void print_list(NodeList head)
  42. {
  43.  NodeList pCurr = head->next;
  44.  while(pCurr)
  45.  {
  46.   printf("%d\n", pCurr->date);
  47.   pCurr = pCurr->next;
  48.  }
  49. }

  50. NodeList union_list(NodeList la, NodeList lb) //合并两链表 并排序
  51. {
  52.  NodeList pa, pb, r;
  53.  pa = la->next; pb = lb->next;
  54.  la->next = NULL; lb->next = NULL;
  55.  while (pa && pb)
  56.  {
  57.   if (pa->date <= pb->date)
  58.   {
  59.    r = pa->next;
  60.    pa->next = la->next;
  61.    la->next = pa;
  62.    pa = r;
  63.   }
  64.   else
  65.   {
  66.    r = pb->next;
  67.    pb->next = la->next;
  68.    la->next = pb;
  69.    pb = r;
  70.   }
  71.  }
  72.  while (pa)
  73.  {
  74.   r = pa->next;
  75.   pa->next = la->next;
  76.   la->next = pa;
  77.   pa = r;
  78.  }
  79.  while (pb)
  80.  {
  81.   r = pb->next;
  82.   pb->next = la->next;
  83.   la->next = pb;
  84.   pb = r;
  85.  }
  86.  return la;
  87. }

  88. int _tmain(int argc, _TCHAR* argv[])
  89. {
  90.  NodeList p1, p2;
  91.  p1 = creat_list_1();
  92.  p2 = creat_list_2();
  93.  print_list(p1);
  94.  print_list(p2);
  95.  union_list(p1, p2);
  96.  printf("\n");
  97.  print_list(p1);
  98. // print_list(p2);

  99.  return 0;
  100. }
阅读(750) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~