Ideas:
Known two pointers head1,head2;
First define the returned pointer head;
Compare the value of data in Head1, and head2, and assign a pointer with a smaller value to head.
A current pointer is defined by
At this point current = head;
Define P1, and the P2 pointer traverses two sequences respectively.
If the two list is initialized, because the value of node 1 is less than the value of Node A, head = node 1,current = Node 1, p1 = node 2, p2 = Node A.
Loops compare the values of the P1 and P2 nodes, connecting the nodes with the smaller values to the previous node. If the value of Node A is less than the value of Node 2, then Current->next = Node A, current = Node A, p2 = p2->next is p2 = Node B. P1 not change. The loop ends when P1 and P2 are empty. Returns the head pointer.
The code is as follows:
#include <stdio.h> #include <stdlib.h>//defines a struct, data is a value struct studentstruct{int data; struct studentstruct * next;}; typedef struct STUDENTSTRUCT student;//key method, passing in two list of head pointers, returning the fused list pointer student * SORTMETHOD (Student * head1,student * head2) { Student * P1=NULL; Student * P2=NULL; Student * HEAD=NULL; if (head1->data>head2->data) {head = head2; P2 = head2->next; P1 = Head1; }else{head = head1; P1 = head1->next; P2 = head2; } Student * current = head; while (!) ( p1== NULL && p2==null) {if (p1==null) {current->next = p2; Break } if (p2==null) {current->next = P1; Break } if (p1->data>p2->data) {current->next = p2; current = P2; P2 = p2->next; }else{current->next = p1; current = P1; P1 = p1->next; }} return Head;} Student * Createonehead (int n) {student * head = NULL; Student * P2 = NULL; Student * P1 = NULL; while (n>0) {p2 = (student *) malloc (sizeof (student)); printf ("Please enter data:\n"); scanf ("%d",& (P2->data)); P2->next = NULL; if (head==null) {head = P2; P1 = head; }else{p1->next = p2; P1 = p2; } n--; } return head; void print (Student * head) {student * p = head; while (P!=null) {printf ("%d\n", p->data); p = p->next; }}int Main () {printf ("Initialize first sequence \ n"); Student *h1 = Createonehead (4); printf ("initialize the 2nd sequence \ n"); Student *H2 = Createonehead (3); Student *head = SortMethod (H1,H2); Print (head); return 0;}
Operation Result:
Combine two well-ordered lists into an ordered list-C language code