#include <stdio.h> #include <stdlib.h> #include <time.h> #include <conio.h> #define N 10 typedef struct Node { int data; struct Node *next; }Node, *pNode; /*顺序插入法*/ void create_list_sequence(pNode *h) { pNode p, q, r=NULL; p = q = *h = (pNode)calloc(1,sizeof(Node)); p->next = NULL; int count = 0; while (count != N){ ++count; if (count == 1){ p->data = rand()%100; //printf("%d ", p->data); } else{ r = (pNode)calloc(1,sizeof(Node)); r->data = rand() % 100; //printf("%d ", r->data); p = q = *h; while (p ->next != NULL && p->data < r->data ){ q = p; p = p->next; } if (p->data >= r->data){ if (p == q){ r->next = *h; *h = r; } else { r->next = p; q->next = r; } } else{ p->next = r; r->next = NULL; } } } printf("\n"); } /*在这个合并俩链表的程序中,除了刚开始,pa1,pa2始终是一前一后,pb1和pb2始终 是b中当前所剩节点的头节点*/ void mergeTwoList(pNode *h1, pNode *h2) { pNode pa1, pa2, pb1, pb2; pa1 = pa2 = *h1; pb1 = pb2 = *h2; while (pa1 != NULL&&pb1 != NULL){/*当两个链表其中任何一个遍历结束, 就退出循环*/ while (pb1->data > pa1->data && pa1->next != NULL){/*找到a 链表中不小于b链表中元素的元素,如果一直没有,则到a中的最后一个元素为止*/ pa2 = pa1; pa1 = pa1->next; } if (pa1->data >= pb1->data){/*找到了a链表中不小于b链表中元 素的元素*/ if (pa1 == pa2){/*如果是a聊表的第一个元素,就把a链 表的头指针指向b链表的第一个节点*/ *h1 = pb1; } else{ pa2->next = pb1;/*如果不是a链表中的第一个元 素,则让a链表当前节点的上一个节点指向b当前节点*/ } pb1 = pb1->next;/*将b1向后移动一个位子,为pb2指向 pa1,从而防止会和b表中下一个节点失去联系*/ pb2->next = pa1; pa2 = pb2; pb2 = pb1; }else{ pa2 = pa1;/*如果a当前元素比b小,且是a中最后一个元素 ,就往后移动,其实就会执行一次,只是是为了解决死循环问题*/ pa1 = pa1->next; } } if (pa1 == NULL && pb1 != NULL){ pa2->next = pb1; } } void mergeTwoList_test() { pNode Link1, Link2; create_list_sequence(&Link1); create_list_sequence(&Link2); printf("Link1:\n"); printList(Link1); printf("Link2:\n"); printList(Link2); mergeTwoList(&Link1, &Link2); printf("After merge:\n"); printList(Link1); } int main() { mergeTwoList_test(); return 0; }
原文地址:http://blog.csdn.net/nyist327/article/details/29810087