如果是双向链表,则除上面操作外,再让第二个链表的 prev指针指向第一个链表最后一个元素
#include<stdio.h>#include<malloc.h>
struct studenta {
int num
float score
struct studenta *next
}
struct studentb {
int num
float score
struct studentb *next
}
struct studenta *add(struct studenta *heada,struct studenta *p0)
{
struct studenta *p1,*p2
p1 = heada
while(/*p1->next!=NULL*/p1!=NULL && p1->num<p0->num) {
p2 = p1
p1 = p1->next
}
if(p1 == heada) {
heada = p0
p0->next = p1
}else {
if(p2->next != NULL) {
// p2->next = p0
// p0->next = p1 /*顺序不要搞错*/
p0->next = p1
p2->next = p0
}else {
p2->next = p0
p0->next = NULL
}
}
return heada
}
int main()
{
struct studenta boya[3], *heada, *p, *p0, *pa
struct studentb boyb[3], *headb, *pb
struct studenta *add(struct studenta *,struct studenta *)
heada = boya
headb = boyb
boya[0].num = 101
boya[0].score = 100.0
boya[1].num = 103
boya[1].score = 98.0
boya[2].num = 105
boya[2].score = 55.0
boya[0].next = &boya[1]
boya[1].next = &boya[2]
boya[2].next = NULL
boyb[0].num = 102
boyb[0].score = 35.0
boyb[1].num = 104
boyb[1].score = 77.0
boyb[2].num = 106
boyb[2].score = 59.0
boyb[0].next = &boyb[1]
boyb[1].next = &boyb[2]
boyb[2].next = NULL
printf("A链表:\n")
pa = heada
do {
printf("num = %d\tscore = %5.1f\n", pa->num, pa->score)
pa = pa->next
} while(pa)// 用heada遍历,循环结束heada已经不再指向头结点
printf("B链表:\n")
pb = headb
do {
printf("num = %d\tscore = %5.1f\n",pb->num,pb->score)
pb = pb->next
} while(pb)// headb遍历,循环结束headb已经不再指向头结点
printf("合并链表:\n")
do {
p0 = (struct studenta *)malloc(sizeof(struct studenta))
p0->num = headb->num
p0->score = headb->score
p = add(heada, p0)
headb = headb->next
} while(headb)
do {
printf("num = %d\tscore = %5.1f\n",p->num,p->score)
p = p->next
} while(p)
return 0
}