本篇文章提供了一个使用C语言实现链表归并排序的数据结构和示例代码,帮助读者理解和掌握链表归并排序的具体操作方法。
在C语言的数据结构学习中,链表归并排序是一个常见的练习题目。本例涉及两个无头节点的单链表(分别由指针ha和hb表示),这两个链表中的数据已经按照递增顺序排列。
任务是将第二个链表hb合并到第一个链表ha中,并且保持整个合并后的列表依然有序,同时如果在ha中有重复的数据,则不从hb中添加这些相同值的节点。在这个过程中不允许破坏原链表Lb的结构。
以下是实现上述功能的一个C语言示例代码:
```c
#include
#include
#define N1 6 // 链表La(由ha指针指向)的长度定义为6个元素。
#define N2 6 // 链表Lb(由hb指针指向)的长度定义为6个元素。
struct listnode {
int data;
struct listnode *next;
};
void mergeLists(struct listnode **heada, struct listnode *headb) {
struct listnode *currentA = (*heada);
struct listnode *previousA = NULL;
while (currentA != NULL && headb != NULL) { // 遍历两个链表直到其中一个为空。
if (currentA->data < headb->data){
previousA = currentA;
currentA = currentA->next;
} else {
struct listnode *tempB = headb;
headb = headb->next;
// 将headb的节点插入到ha链表中
if (previousA != NULL) {
previousA->next = tempB;
tempB->next = currentA;
} else {
tempB->next = (*heada);
*heada = tempB;
}
}
}
// 如果ha链表遍历结束而hb还有剩余节点,直接将剩下的部分接在后面
if (currentA == NULL) previousA->next = headb;
}
void printList(struct listnode* node)
{
while(node != NULL){
printf(%d , node->data);
node = node->next;
}
}
int main() {
// 初始化链表ha和hb
struct listnode *heada, *currentA;
heada = (struct listnode*)malloc(sizeof(struct listnode));
currentA = heada;
for(int i=0; idata=i*2+3;
if(i==N1-1) { // 最后一个节点
currentA->next=NULL;
} else {
struct listnode *temp=(struct listnode*)malloc(sizeof(struct listnode));
temp->next = NULL;
currentA->next=temp;
currentA=currentA->next;
}
}
struct listnode *headb, *currentB;
headb = (struct listnode*)malloc(sizeof(struct listnode));
currentB=headb;
for(int i=0; idata=i*3+1;
if(i==N2-1) { // 最后一个节点
currentB->next=NULL;
} else {
struct listnode *temp=(struct listnode*)malloc(sizeof(struct listnode));
temp->next = NULL;
currentB->next=temp;
currentB=currentB->next;
}
}
mergeLists(&heada, headb);
printf(合并后的链表:);
printList(heada);
return 0;
}
```