6-4 链表拼接 (20 point(s))
本题要求实现一个合并两个有序链表的简单函数。链表结点定义如下:
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 § {
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
Author
张泳
Organization
浙江大学
Code Size Limit
16 KB
Time Limit
400 ms
Memory Limit
64 MB
void sort(struct ListNode *p)
{
struct ListNode *q, *temp = p;
int change;
int min;
int flag = 0;
for (p; p->next != NULL; p = p->next){
min = p->data;
//下面的注释为第二种写法,当后面找到最小值的时候,才进行交换,否则,不需要条件交换会乱序
//flag = 0;
temp = p;//temp不归位的话,下面的交换程序仍然会继续执行,指向的值在不满足条件的情况下也会交换
for (q = p->next; q != NULL; q = q->next)
if (q->data < min){
min = q->data;//
temp = q;
//flag = 1;
}
/* if(flag == 1){
change = temp->data;
temp->data = p->data;
p->data = change;
}*/
change = temp->data;
temp->data = p->data;
p->data = change;
}
}
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2)
{
struct ListNode *p;
if(list1 == NULL)
if(list2 != NULL){
sort(list2);
return list2;
}
else
return list1;
else{
p = list1;
while (p->next != NULL)
p = p->next;
p->next = list2;
sort(list1);
return list1;
}
}