Data structure experiment linked list 4: merging ordered linked lists
Data structure experiment linked list 4: merging ordered linked lists Time Limit: 1000 MS Memory limit: 65536 K Enter two ordered integer sequences (including M and N data) to create two ordered Single-Chain tables, merge the two ordered Single-Chain tables into a large ordered single-chain table, and output the merged single-chain table data in sequence. Enter the values of M and N in the first line;
In the second row, enter M ordered integers in sequence;
In the third row, enter N ordered integers in sequence. Output The M + N ordered integers contained in the merged single-chain table. Sample Input
6 51 23 26 45 66 9914 21 28 50 100
Sample output
1 14 21 23 26 28 45 50 66 99 100
An array is not allowed! Source
Sample program
# Include
# Include
Struct node {int data; struct node * next;}; // create a sequence linked list struct node * Creat (int n) {struct node * head, * tail, * p; int I; head = (struct node *) malloc (sizeof (struct node); head-> next = NULL; tail = head; for (I = 1; I <= n; I ++) {p = (struct node *) malloc (sizeof (struct node); scanf ("% d", & p-> data ); p-> next = NULL; tail-> next = p; tail = p;} return head;} struct node * Merge (struct node * head1, struct node * head2) {struct n Ode * p1, * p2, * tail; p1 = head1-> next; p2 = head2-> next; tail = head1; free (head2); while (p1 & p2) {if (p1-> data <p2-> data) {tail-> next = p1; tail = p1; p1 = p1-> next ;} else {tail-> next = p2; tail = p2; p2 = p2-> next ;}} if (p1) tail-> next = p1; else tail-> next = p2; return (head1);} int main () {struct node * head1, * head2, * p; int n, m; scanf ("% d", & n, & m); head1 = Creat (n); head2 = Creat (m); p = Merge (head1, head2); while (P-> next! = NULL) {printf ("% d", p-> next-> data); p = p-> next;} printf ("% d \ n ", p-> next-> data); return 0 ;}