#include <stdio.h>
#include<stdlib.h>
typedef struct student {
int num;
float score;
struct student* pnext;
}stu, * pstu;
void list_print(pstu phead)
{
while (phead)
{
printf("%d %5.1f\n", phead->num, phead->score);
phead = phead->pnext;
}
}
void list_sort_insert(pstu* pphead, stu** pptail, int i) {
pstu pnew = (pstu)calloc(1, sizeof(stu));
pnew->num = i;
pstu pcur, ppre;
pcur = ppre = *pphead;
if (*pphead == NULL) { *pphead = pnew; *pptail = pnew; } //链表为空,头尾指针指向新节点
else if (i < (*pphead)->num) { pnew->pnext = *pphead; *pphead = pnew; } //判断是否插入头部,头插法
else { //否则插入
while (pcur) {
if (i > (pcur->num)) { ppre = pcur; pcur = pcur->pnext; } //插入值大于pcur->num,ppre指向pcur,pcur指向下一个节点
else { ppre->pnext = pnew; pnew->pnext = pcur; break; } //ppre节点的pnext指向新节点,新节点的pnext指向pcur
}
if (pcur == NULL) { (*pptail)->pnext = pnew; *pptail = pnew; } //插入到尾部,尾插法
}
}
pstu listmerge(pstu head1, pstu head2) //合并两个有序链表
{
pstu head = NULL, tail = NULL;
if (head1 == NULL) return(head = head2); //第一个链表为空,返回第二个链表
else if (head2 == NULL) return(head = head1); // 第二个链表为空,返回第一个链表
else
{
if (head1->num <= head2->num) //将head指向较小的头节点,并将该头节点后移
{ head = head1;
head1 = head1->pnext;
}else{
head = head2;
head2 = head2->pnext;
}
tail = head;
while (head1 != NULL && head2 != NULL) //两链表都非空
{
if (head1->num <= head2->num) {
tail->pnext = head1; //尾节点next指向较小的头节点
tail = head1; //该头节点作为新的尾节点
head1 = head1->pnext; //头节点后移一位
}
else {
tail->pnext = head2;
tail = head2;
head2 = head2->pnext;
}
}
tail->pnext = (head1 == NULL) ? head2 : head1; //尾节点指向剩下非空的链表头节点
return head;
}
}
int main() {
pstu phead1, phead2, ptail1, ptail2;
phead1 = ptail1 = NULL;
phead2 = ptail2 = NULL;
int i, m;
printf("list1:");
while (scanf_s("%d", &i) != EOF)
{
list_sort_insert(&phead1, &ptail1, i);
}
list_print(phead1);
printf("list2:");
while (scanf_s("%d", &m) != EOF)
{
list_sort_insert(&phead2, &ptail2, m);
}
list_print(phead2);
printf("合并后的链表:\n");
list_print(listmerge(phead1, phead2));
return 0;
}
合并两个有序链表
最新推荐文章于 2024-04-01 09:00:40 发布