链表的基本操作合并,逆转:
一:两个有序链表的合并(顺序从小到大依次排列)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <time.h> 5 6 typedef struct tag 7 { 8 int Nnum_; 9 struct tag *Nnext_; 10 }Node, *pNode; 11 12 13 void link_print(pNode phead) 14 { 15 while(phead != NULL) 16 { 17 printf("%4d", phead->Nnum_); 18 phead = phead->Nnext_; 19 } 20 printf("\n"); 21 } 22 23 24 void link_insert_by_sort(pNode *phead, int size) 25 { 26 pNode pNew = NULL; 27 pNode pCur, pPre; 28 29 while( size > 0 ) 30 { 31 pNew = (pNode)malloc(sizeof(Node)); 32 pNew->Nnum_ = rand()%1000; 33 34 pPre = NULL; 35 pCur = *phead; 36 while( pCur != NULL) 37 { 38 if( pNew->Nnum_ > pCur->Nnum_) //按照从小到大排序 39 { 40 pPre = pCur; 41 pCur = pCur->Nnext_; 42 } 43 else //找到位置 44 break; 45 } 46 //找到的位置在头部 47 if( pPre == NULL) 48 { 49 pNew->Nnext_ = *phead; 50 *phead = pNew; 51 }else//位置在中间或者尾部 52 { 53 pPre->Nnext_ = pNew; 54 pNew->Nnext_ = pCur; 55 } 56 size --; 57 } 58 } 59 60 void link_merge(pNode *pLeft, pNode *pRight)//采用尾插法 61 { 62 pNode pLeft_cur = *pLeft, pLeft_tail; 63 *pLeft = NULL; //置空 64 pLeft_tail = NULL; 65 66 pNode pRight_cur = *pRight; 67 68 while( pLeft_cur != NULL && pRight_cur!= NULL) 69 { 70 if( pLeft_cur->Nnum_ < pRight_cur->Nnum_) //如果左链表元素值小于右链表元素值 71 { 72 if( *pLeft == NULL)//目前为空 73 { 74 *pLeft= pLeft_cur; //赋值 75 pLeft_tail = pLeft_cur;//增加个名字 76 pLeft_cur = pLeft_cur->Nnext_;//向前移动 77 }else //已经存在 78 { 79 pLeft_tail->Nnext_ = pLeft_cur; //连接 80 pLeft_tail = pLeft_cur; 81 pLeft_cur = pLeft_cur->Nnext_; 82 } 83 } 84 else//如果左链表元素值大于或者等于右链表元素值 85 { 86 if( *pLeft == NULL)//目前为空 87 { 88 *pLeft= pRight_cur;//赋值 89 pLeft_tail = pRight_cur; 90 pRight_cur = pRight_cur->Nnext_; 91 } 92 else//非空 93 { 94 pLeft_tail->Nnext_ = pRight_cur;//连接 95 pLeft_tail = pRight_cur; 96 pRight_cur = pRight_cur->Nnext_; 97 } 98 } 99 } 100 if( pLeft_cur ==NULL) //连接右链表剩余的元素 101 pLeft_tail->Nnext_ = pRight_cur; 102 103 if( pRight_cur == NULL)//连接左链表剩余的元素 104 pLeft_tail->Nnext_ = pLeft_cur; 105 } 106 107 int main(int argc, char const *argv[]) 108 { 109 srand(time(NULL)); 110 pNode phead = NULL; 111 link_insert_by_sort(&phead,10); 112 link_print(phead); 113 114 pNode poher = NULL; 115 link_insert_by_sort(&poher,12); 116 link_print(poher); 117 118 link_merge(&phead, &poher); 119 link_print(poher); 120 return 0; 121 }
时间: 2024-11-14 20:17:55