16 linked list - merging two sorted linked lists

Topic Description

Input two monotonically increasing linked lists, output two combined linked lists, of course, we need to synthesize the linked list to meet the monotonic rule.

Analysis:

// Merge two monotone linked lists into one linked list
// The length of the two lists is the same, Q1 pair q2 is long, q2 is longer than q1, whether it is empty or not;
// Consider that the length of the two lists is the same first, and then consider that the length of the list is different.

Ideas:

 

Complete code

There's still something wrong with the code, to be debugged

#include<stdio.h>
#include<malloc.h> 
/*Single linked list implementation: merging two sorted linked lists*/ 
typedef struct Link
{
	char elem;    //Represents data domains
	struct Link * next;  //Represents a pointer field, pointing to a direct successor element 
}link;

link *init();
link *init2();
link *combine();

int main(){
	link *phead1;
	phead1 = init();
	link *phead2 = init2();
	link *phead = combine(phead1,phead2);
	while(phead != NULL){
//		phead = phead->next;
		printf("%d\n",phead->elem);
		phead = phead->next;
	}
	return 0;
}

link *init(){
	link *head = (link *)malloc(sizeof(link));
	head->next = NULL;
	link *temp = head;
	int i;
	for(i=1;i<8;)
	{
		link *body = (link *)malloc(sizeof(link));
		body->next = NULL;
		body->elem = i;
		i=i+2;
		temp->next = body;
//		printf("p1:%d ",temp->elem);
		temp= temp->next;
		printf("p1:%d ",temp->elem);
	}
	return head;
}

link *init2(){
	link *head = (link *)malloc(sizeof(link));
	head->next = NULL;
	link *temp = head;
	int i;
	for(i=0;i<8;)
	{
		link *body = (link *)malloc(sizeof(link));
		body->next = NULL;
		body->elem = i+2;
		i=i+2;
		temp->next = body;
		
		temp= temp->next;
		printf("p2:%d ",temp->elem);
	}
	return head;
}

link *combine(link *q1,link *q2){
	link *q =  (link *)malloc(sizeof(link));
	q->next = NULL;
	link *temp = q;
	int flag = 0;
	//Merge two monotone linked lists into one linked list
	//The length of the two lists is the same, Q1 pair q2 is long, q2 is longer than q1, whether it is empty or not;
//	Consider that the length of the two lists is the same first, and then consider that the length of the list is different.
	if(q1 == NULL){
		return q2;
	 } 
	 if(q2 == NULL){
	 	return q1;
	 }
//	 First determine the header node 
	 while(q1 && q2){
	 	 
	 	if(q1->elem <= q2->elem){
	 		//Initialization node 
	 		link *body = (link *)malloc(sizeof(link));
	 		body->next = NULL;
	 		body->elem = q1->elem;
	 		//New Nodes 
	 		temp->next = body;
	 		//Point to the next node 
	 		temp = temp->next;	
	 		flag = 0;
		}
		 else{
		 	link *body = (link *)malloc(sizeof(link));
	 		body->next = NULL;
	 		body->elem = q2->elem;
	 		temp->next = body;
	 		temp = temp->next;	
	 		flag  = 1;
		}
		
		 if(flag == 0){
		 	q1 = q1->next;
		 } else{
		 	q2 = q2->next;
		 }
		 
	 }
	 
	 return q;
}

Result

Posted by bios on Tue, 30 Jul 2019 16:12:19 -0700