题目1519:合并两个排序的链表

写链表就是不停的调。。。发现问题就改。。。蓝后就行了!!!

链表的合并而已

#include
#include
#include

typedef struct node
{
	int val;
	struct node *next;
}Sqlist;

int n,m;

Sqlist *create(int n)
{
	if(n == 0)
		return NULL;
	Sqlist *l1,*l2,*head;
	l1 = (Sqlist *)malloc(sizeof(Sqlist));
	scanf("%d",&l1->val);
	head = l2 = l1;
	for(int i=1;ival);
		l2->next=l1;
		l2=l1;
	}
	l2->next = NULL;
	return head;
}

Sqlist *merge(Sqlist *l1,Sqlist *l2)
{
//	printf("--");
	Sqlist *l,*head;
	if(l1 == NULL)
	{
		l = head = l2;
		l2 = l2->next;
	}
	if( l2 == NULL)
	{
		l = head = l1;
		l1 = l1->next;
	}
	if(l1 != NULL && l2 != NULL && l1->val < l2->val)
	{
		l = head = l1;
		l1 = l1->next;
	}
	else if(l1 != NULL && l2 != NULL && l1->val > l2->val)
	{
		l = head = l2;
		l2 = l2->next;
	}
	while(l1 != NULL && l2 != NULL)
	{//printf("--");
		if(l1->val < l2->val)
		{
			l->next = l1;
			l = l1;
			l1 = l1->next;
		}
		else
		{
			l->next= l2;
			l = l2;
			l2=l2->next;
		}
	}
	while(l1 != NULL)
	{
		l->next = l1;
		l = l1;	
		l1 = l1->next;
	}
	while(l2 != NULL)
	{
		l->next= l2;
		l = l2;
		l2 = l2->next;
	}
	l->next = NULL;
	return head;
}

int main()
{
	while(scanf("%d%d",&n,&m) != EOF)
	{
		if(n == 0 && m == 0)
		{
			printf("NULL\n");
			continue;
		}
		Sqlist *list1,*list2,*list;
		list1 = create(n);
		
		list2 = create(m); 
	 
		list = merge(list1,list2);
		while(list->next != NULL)
		{
			printf("%d ",list->val);
			list = list->next;
		}
		printf("%d\n",list->val);
	}
	return 0;
}


你可能感兴趣的:(九度,剑指OFFER)