- 论坛徽章:
- 0
|
这个是第2题的实现,还有测试的样例。
#include <stdio.h>
#include <stdlib.h>
#define N 3
#define M 4
struct list
{
int value;
list *next;
};
list *merge(list *list1_head, list *list2_head);
list *insert_back(list *head, int value);
list *insert_front(list *head, int value);
void print_list(list *head);
int main()
{
list *head1 = NULL, *head2 = NULL, *head3 = NULL;
int x1[ N ] = { 9, 7, 5 };
int x2[ M ] = { 8, 6, 4, 1 };
int i;
for (i = 0; i < N; ++i)
{
head1 = insert_back(head1, x1[ i ]); // 这个是x1 [ i ] 有i下标的,显示时竟然显示不出来
}
for (i = 0; i < M; ++i)
{
head2 = insert_back(head2, x2[ i ]); // 这个是x2 [ i ] 有i下标的,显示时竟然显示不出来
}
head3 = merge(head1, head2);
print_list(head3);
return 0;
}
list *merge(list *list1_head, list *list2_head)
{
list *p1 = list1_head, *p2 = list2_head, *q = NULL;
while (p1 != NULL && p2 != NULL)
{
if (p1->value >= p2->value)
{
q = insert_front(q, p1->value);
p1 = p1->next;
}
else
{
q = insert_front(q, p2->value);
p2 = p2->next;
}
}
if (p1 == NULL && p2 != NULL)
{
while (p2 != NULL)
{
q = insert_front(q, p2->value);
p2 = p2->next;
}
}
if (p2 == NULL && p1 != NULL)
{
while (p1 != NULL)
{
q = insert_front(q, p1->value);
p1 = p1->next;
}
}
return q;
}
list *insert_back(list *head, int value)
{
list *p = head, *q;
q = (list *) malloc(sizeof(list));
q->value = value;
q->next = NULL;
if (p == NULL)
{
head = q;
return head;
}
while (p->next != NULL)
{
p = p->next;
}
p->next = q;
return head;
}
list *insert_front(list *head, int value)
{
list *p = head, *q;
q = (list *) malloc(sizeof(list));
q->value = value;
if (p == NULL)
{
q->next = NULL;
head = q;
return head;
}
else
{
q->next = head;
head =q;
return head;
}
}
void print_list(list *head)
{
list *p = head;
while (p != NULL)
{
printf("%d\n", p->value);
p = p->next;
}
}
[ 本帖最后由 ispexceed 于 2009-9-10 14:23 编辑 ] |
|