线性单链表的功能实现
#include<stdio.h>
#include<stdlib.h>
//线性表的单链表存储结构
typedef struct LNode {
int data;
struct LNode* next;
}LNode, * LinkList;//*LinkList :LinkList L 相当于struct LNode * L;
//初始化
/*void InitLink(LinkList L) {
L->next = nullptr;
}*/
//建立单链表
void CreateList_L(LinkList L, int n) {
LinkList p = nullptr;
L = (LinkList)malloc(sizeof(LNode));
L->next = nullptr;
//生成新节点
for (int i = 1; i <= n; i++) {//头插法,自己可以画图理解一下过程
p = (LinkList)malloc(sizeof(LNode));
p->data = i;
p->next = L->next;
L->next = p;
}
}
//取得第i个数据元素
void GetElem_L(LinkList L, int i, int& e) {
//L是带头节点的单链表的头指针
LinkList p = L->next;
int j = 1;
while (p && j < i) {
p = p->next;
++j;
}
if (!p || j > i) exit(0);//第i个元素不存在
e = p->data;
}
//插入
void ListInsert_L(LinkList L, int i, int e) {
//在第i个位置前插入元素e
LinkList p = L;
LinkList s = nullptr;
int j = 0;
while (p && j < i - 1) {//寻找第i-1个结点
p = p->next;
++j;
}
if (!p || j > i - 1) exit(0);
s = (LinkList)malloc(sizeof(LNode));//生成新节点
s->next = p->next;//操作
s->data = e;
p->next = s;
}
//删除
void ListDelete_L(LinkList L, int i, int& e) {
//删除第i个节点并返回删除节点的值
LinkList p = L;
LinkList q = nullptr;
int j = 0;
while (p->next && j < i - 1) {
p = p->next;
++j;
}
if (!(p->next) || j > i - 1) exit(0);
q = p->next;//操作
p->next = q->next;
e = q->data;
free(q);
}
//将2个链表合并
void MergeList_L(LinkList La, LinkList Lb, LinkList Lc) {
//la lb 按值非递减排序
LinkList pa, pb, pc;
pa = La->next;
pb = Lb->next;
Lc = pc = La;//用La的头节点作为Lc的头节点
while (pa && pb) {
if (pa->data <= pb->data) {
pc->next = pa;
pc = pa;
pa = pa->next;
}
else {
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
free(Lb);
}
结果: