Data structure experiment linked list 4: merging ordered linked lists

Source: Internet
Author: User

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 ;}
  
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.