天天看点

链表连接(将两个有序链表合成一个链表)

#include<stdio.h>
#include<stdlib.h>
typedef struct str {
	int data;
	struct str *next;
} list;
list *creatlist(int length,bool a);
void displaylist(list *head);
list *connectlist(list *a,list *b);
int main() {
	list *a1=creatlist(12,true);
	list *a2=creatlist(12,false);

	list *test=connectlist(a1,a2);
	displaylist(test);
	return 0;
}
list *creatlist(int length,bool a) {
	list *head=(list*)malloc(sizeof(list));
	list *p,*q;
	p=head;
	if(a==true) {
		for(int i=1; i<length; i+=2) {
			q=(list*)malloc(sizeof(list));
			q->data=i;
			q->next=NULL;
			p->next=q;
			p=q;
		}
		return head;
	} else {
		for(int i=2; i<length; i+=2) {
			q=(list*)malloc(sizeof(list));
			q->data=i;
			q->next=NULL;
			p->next=q;
			p=q;
		}
		return head;
	}
}

void displaylist(list *head) {
	while(head->next!=NULL) {
		head=head->next;
		printf("%d",head->data);
	}
}
list *connectlist(list *a,list *b) {
	list *head=(list*)malloc(sizeof(list));
	list *c=head;
	a=a->next;
	b=b->next;
	for(; a!=NULL&&b!=NULL;) {
		if(a->data<b->data) {
			head->next=a;
			head=a;
			a=a->next;
		} else {
			head->next=b;
			head=b;
			b=b->next;
		}
	}
	if(a==NULL){
		head->next=b;
	}
	else{
		head->next=a;
	}
	return c;
}









           

继续阅读