Given two ordered single-linked lists, merging the two single-linked lists, the linked list is still ordered.
For example, give the list 1:1->3->6->7; linked list 2:2->4->5->8->9
The linked list after merging is: 1->2->3->4->5->6->7->8->9
The code is shown below (only the implementation part is given)
Structure definition:
typedef struct LINKNODE{DATATYPE data;struct Linknode *next;} linknode,*plinknode;typedef struct Linklist{linknode *phead;} Linklist,*plinklist;
Function implementation:
Plinknode mergelinklist (plinklist L1, plinklist L2) {assert (L1 && L2);p Linknode cur1 = L1->phead;plinknode CUR2 = L2->phead;plinknode p = Null;plinknode tail = null;//Handling exception if (null = = Cur1 && NULL = = CUR2) {return null ;} if (Cur1 = = NULL) {return cur2;} if (NULL = = cur2) {return cur1;} if (Cur1->data < cur2->data) {p = cur1;cur1 = Cur1->next;tail = P;} Else{p = CUR2;CUR2 = Cur2->next;tail = P;} while (Cur1 && cur2) {if (Cur1->data < cur2->data) {Tail->next = Cur1;cur1 = cur1-Next;tail = tail ->next;} Else{tail->next = CUR2;CUR2 = Cur2->next;tail = Tail->next;}} while (CUR1) {tail->next = Cur1;break;} while (CUR2) {tail->next = Cur2;break;} return p;}
Code Analysis: The program starts with exception handling. The last two while loops can only execute at most one, and there are
Non-performing cases. This is a better understanding, not to mention.
Based on the above approach, we can deal with a problem like this: merging two ordered arrays and merging the knot
Fruit put in array 1 (array 1 is sufficient to store all elements of two arrays). Look at the code below:
void merge (int num1[], int m, int num2[], int n) {assert (m>0&&n>0); int i = 0;int j = 0;int k = 0;int *arr = ( int *) malloc (sizeof (int) * (m+n)), while (I < M&&j < n) {if (Num1[i] < num2[j]) {arr[k] = num1[i];k++;i++;} Else{arr[k] = num2[j];k++;j++;}} while (I < m) {arr[k++] = arr[i++];} while (J < n) {arr[k++] = arr[j++];} memcpy (num1,arr,10*sizeof (int));}
To reduce the number of moving elements, we use space-time-----to open up a new array to save the merged
element, and finally copies the elements in the new array to array 1 using the memory copy function.
Merging of two ordered single-linked lists