1.单链表的建立与头插法的使用
- 下面是具体实现代码(可实现代码)
#include <stdio.h> #include <malloc.h> typedef int ElemType; typedef struct LNode { //单链表的结构体 ElemType data; struct LNode* next; }LNode,*LinkList; //将两个递增单链表合并成一个单链表,结果链表仍使用原来的空间,不占用其它存储空间 LinkList CreatList(LinkList L) { //用头插法建立单链表 n为创建单链表所需的元素个数 int n; LNode *s;//工作指针 L = (LinkList)malloc(sizeof(LNode)); L->next = NULL; scanf_s("%d", &n);//输入建立单链表的值 while (n!=999)//循环终止条件 { s = (LinkList)malloc(sizeof(LNode)); s->data = n; //插入数据元素 //头插法的使用 s->next = L->next; L->next = s; scanf_s("%d", &n); } return L; } //打印单链表 void PrintList(LinkList L) { L = L->next; printf("建立的单链表为:\n"); while (L) { printf("%d", L->data); L = L->next; } } int main() { LinkList s1;//建立s1单链表 s1 = (LinkList)malloc(sizeof(LNode));//为单链表动态分配存储空间 s1 = CreatList(s1); PrintList(s1); }
2.单链表尾插法的使用
- 下面是具体代码实现
LinkList CreatList(LinkList &L) {
//使用尾插法建立单链表
L = (LinkList)malloc(sizeof(LNode));
LNode *s;//工作指针
LNode* r=L;//表尾指针
int x;
scanf_s("%d", &x);//输入X的值
while (x!=999)
{
s = (LinkList)malloc(sizeof(LNode));
s->data = x;
//尾插法
r->next = s;
r = s;
scanf_s("%d", &x);
}
return L;
}
3.合并单链表
可执行源代码
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct LNode {
// 单链表的结构体
ElemType data;
struct LNode* next;
} LNode, * LinkList;
LinkList CreatList(LinkList& L) {
// 使用尾插法建立单链表
L = (LinkList)malloc(sizeof(LNode));
LNode* s; // 工作指针
LNode* r = L; // 表尾指针
int x;
scanf_s("%d", &x); // 输入X的值
while (x != 999) {
s = (LinkList)malloc(sizeof(LNode));
s->data = x;
// 尾插法
r->next = s;
r = s;
scanf_s("%d", &x);
}
r->next = NULL; // 尾节点指针置空
return L;
}
// 打印单链表
void PrintList(LinkList L) {
int x;
L = L->next;
printf("建立的单链表为:\n");
while (L) {
printf("%d\n", L->data, sizeof(x));//加了一个缓冲区,用的scanf_s来输入
L = L->next;
}
}
void MergerLinkList(LinkList L1,LinkList L2) {
LNode* La, * Lb;
LNode* pa,* pb;
La = L1->next;
pa = L1;//l1的头指针
Lb = L2->next;
pb = L2;//L2的头指针
while (La != NULL && Lb != NULL)
{
if (La->data <= Lb->data) {
La = La->next;
pa = pa->next;
}
else if (La->data > Lb->data)
{
// LNode* temp = Lb->next; // 保存Lb的后继结点
pb = Lb; //保留Lb的后继指针
Lb = Lb->next;
pb->next = La;
pa->next = pb;
pa = pa->next;
}
}
if (Lb!= NULL) {
pa->next = Lb; // 将Lb剩余的结点插入到La的末尾
}
free(Lb);
}
int main() {
LinkList s1, s2;//s1单链表
s1 = (LinkList)malloc(sizeof(LNode)); // 为单链表动态分配存储空间
s2 = (LinkList)malloc(sizeof(LNode));
s1 = CreatList(s1);
PrintList(s1);
s2 = CreatList(s2);
PrintList(s2);
MergerLinkList(s1, s2);
PrintList(s1);
return 0;
}