6-3 链表拼接 (20分)

本题要求实现一个合并两个有序链表的简单函数。链表结点定义如下:

struct ListNode {
    int data;
    struct ListNode *next;
};

函数接口定义:

#include 
#include 

struct ListNode {
    int data;
    struct ListNode *next;
};

struct ListNode *createlist(); /*裁判实现,细节不表*/
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2);
void printlist( struct ListNode *head )
{
     struct ListNode *p = head;
     while (p) {
           printf("%d ", p->data);
           p = p->next;
     }
     printf("\n");
}

int main()
{
    struct ListNode  *list1, *list2;

    list1 = createlist();
    list2 = createlist();
    list1 = mergelists(list1, list2);
    printlist(list1);
	
    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

1 3 5 7 -1
2 4 6 -1

输出样例:

1 2 3 4 5 6 7 

代码

struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2)
{
	struct ListNode *p,*head,*tail;
	head=tail=NULL;
	while(1)
	{
		p=(struct ListNode*)malloc(sizeof(struct ListNode));
		if(list1 ==NULL||list2 ==NULL)
			break;
		if((list1->data) > (list2->data))
			{
			p->data=list2->data;
			list2=list2->next;
			}
		else
		{
			p->data=list1->data;
			list1=list1->next;
		}
        if(head==NULL)
        {
            head=p;
        }
        else
		{
            tail->next=p;
        }
        p->next=NULL;
        tail =p;
	}
	if(list1!=NULL)
		tail->next=list1;
	if(list2!=NULL)
		tail->next=list2;
	return head;
}

你可能感兴趣的:(链表)