将两个升序链表归并为一个链表,其结果仍为升序
代码思想:
将两个已为升序的链表合并为一个升序链表,用头插法插入head1链表,用尾插法插入head2链表,然后在Lump函数中比较并归并。
代码逻辑:
头插或尾插后两个链表都是升序,然后在Lump函数中对其操作。先定义4个指针,其中在插入时,t用来指向插入后应被删除的结点。p,p1,p2,分别用来指向Head,head1,head2的第一个结点;当p1,p2同时不为空时,比较其id,将较小的结点用尾插法插入Head中,然后free(t)并令t=NULL。
当两个链表中有一个链表被遍历完时,用尾插法插入另一个链表的剩余节点,删除应被删除的结点并令其置空。
#include <stdio.h>
#include <malloc.h>
#include <string.h>
typedef struct _STU
{
int id;
char name[32];
int score;
struct _STU* next;
}STU,*PSTU;
void show(const PSTU phead)
{
PSTU pos = phead;
while (pos != NULL)
{
printf("%d,%s,%d", pos->id, pos->name, pos->score);
pos = pos->next;
puts("");
}
}
void InsertHead(PSTU* pphead, int id, char name[],