实验11-2-5 链表拼接 (20 分)
本题要求实现一个合并两个有序链表的简单函数。链表结点定义如下:
struct ListNode {
int data;
struct ListNode *next;
};
函数接口定义:
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2);
其中list1和list2是用户传入的两个按data升序链接的链表的头指针;函数mergelists将两个链表合并成一个按data升序链接的链表,并返回结果链表的头指针。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
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;
}
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2)
{
struct ListNode *head,*pnew,*px,*temp;
if(list1==NULL) return list2;
if(list2==NULL) return list1;
if(list1->data >= list2->data)
{
head = list2;
pnew = list2;
px = list1;
}
else
{
head=list1;
pnew=list1;
px=list2;
}
while(1)
{
while(pnew -> next != NULL && pnew->next->data <= px->data)
{
pnew = pnew->next;
}
if(pnew -> next == NULL)
{
pnew -> next = px;
return head;
}
else
{
temp = pnew->next;
pnew -> next = px;
pnew = px;
px = temp;
}
}
}