Merge two linked lists in ascending order

Source: Internet
Author: User
Two linked lists have been created, and both are written in ascending order of student numbers. A function is required to merge the two linked lists in ascending order. # Include <stdlib. h>
# Include <stdio. h>
# Include <conio. h>
# Include <ctype. h>

# Define Len sizeof (struct student)

Extern unsigned _ floatconvert;/* prevents floating point formats not linked errors */
# Pragma extref _ floatconvert

Typedef struct student
{
Long num;
Float score;
Struct student * next;
} Stu;

Stu * createend ()
{
Int n = 0;
Stu * P1, * P2, * head;
Head = NULL;
P1 = (Stu *) malloc (LEN);/* create the first node */
Scanf ("% lD, % F", & P1-> num, & P1-> score );
P1-> next = NULL;
While (P1-> num! = 0)/* add nodes to the linked list */
{
++ N;
If (n = 1)/* is the first node as the header */
Head = p1;
Else/* not the first node, end as the table */
P2-> next = p1;
P2 = p1;
P1 = (Stu *) malloc (LEN);/* open the next node */
Scanf ("% lD, % F", & P1-> num, & P1-> score );
P1-> next = NULL;
}
Free (P1);/* release the memory occupied by the last node */
Return (head);/* return the head pointer of the linked list */
}

Void print (Stu * head)
{
Stu * P;
P = head;
Do
{
Printf ("% LD \ t % 5.1f \ n", p-> num, p-> score );
P = p-> next;
} While (P! = NULL );
}

Stu * Merge (Stu * P1, Stu * P2)
{
Stu * P, * head;
If (P1-> num <P2-> num)
{
Head = P = p1; P1 = p1-> next ;}
Else
{
Head = P = P2; P2 = P2-> next ;}
While (P1! = NULL & p2! = NULL)
If (P1-> num <P2-> num)
{
P-> next = p1;
P = p1;
P1 = p1-> next;
}
Else
{
P-> next = P2;
P = P2;
P2 = P2-> next;
}
If (P1! = NULL)
P-> next = p1;
Else
P-> next = P2;
Return head;
}

Void main ()
{
Stu * P1, * P2, * head;
Printf ("Please input first link information: \ n ");
P1 = createend ();
Print (P1 );
Printf ("\ nplease input second link information: \ n ");
P2 = createend ();
Print (P2 );
Printf ("\ nthe merged link is: \ n ");
Head = Merge (P1, P2 );
Print (head );
Getch ();
}

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.