1.定义:
2.代码实现:
//链表存储
#define NULL 0
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode, *LinkList;
创建单链表:
//创建线性表,使用尾插法
void createList(LinkList &L, int n)
{
//建立一个带头节点的单链表
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
LinkList r = L;//r指针总是指向当前线性表的最后一个元素,即尾元素
printf("请输入%d个数据:\n", n);
for (int i = 0; i < n; i++)
{
LinkList s = (LinkList)malloc(sizeof(LNode));
scanf("%d", &s->data);
s->next = NULL;
r->next = s;
r = s;
}
}
//整体创建 头插法
void createListHead(LinkList &L, int n)
{
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
printf("请输入%d个数据:\n", n);
for (int i = 0; i < n; i++)
{
LinkList s = (LinkList)malloc(sizeof(LNode));
scanf("%d", &s->data);
s->next = L->next;
L->next = s;
}
}
打印链表:
//打印链表
void printList(LinkList L)
{
printf("打印线性链表:");
LinkList p = L ->next;
while (p)
{
//p为当前查访的元素
printf("%d", p->data);
p=p->next;
}
printf("\n");
}
插入:(注意找位置;指针域的改变)
//插入元素
void insertList(LinkList &L, int i, ElemType e)
{
int j = 1;
LinkList p = L; //指向头节点
while (p &&j < i)//寻找第i个位置,准备插入
{
p = p->next;
j++;
}
if (!p || j > i)
{
printf("插入位置错误");
}
else
{
LinkList s = (LinkList)malloc(sizeof(LNode));
s->data = e;
s->next = p->next; //将p的后继赋给s的后继
p->next = s; //将s赋给p的后继
}
}
删除指定位置元素:
//删除元素
void deleteList2(LinkList &L, int i)
{
int j = 1;
LinkList p, q;
p = L;
while (p->next && j < i)//寻找位置
{
p = p->next;
++j;
}
if (!(p->next) || j > i)
{
printf("位置错误");
}
else
{
q = p->next;
p->next = q->next;
//e = q->data;
free(q);
}
}
整链表删除:
//删除列表
void ClearList(LinkList &L)
{
LinkList p,q;
p = L->next;//指向第一个节点
while (p)
{
q = p->next;
free(p);
p = q;
}
L->next = NULL;
printf("删除完毕\n");
}
合并操作:
//合并两个线性表merge
void mergeList(LinkList &La, LinkList &Lb, LinkList &Lc)
{
Lc = La; //将La的头结点作为Lc的头结点
LinkList pa = La->next;
LinkList pb = Lb->next;
LinkList pc = Lc; //pc总是指向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);//释放b的头节点
}
无重复的:
void unionList(LinkList &La, LinkList &Lb) {
LinkList pa = La->next;
LinkList pb = Lb->next;
LinkList pc = La;//pc总是指向并集列表的最后一个节点
while (pa&&pb) {
if (pa->data < pb->data) {
pc->next = pa;
pc = pa;
pa = pa->next;
}
else if (pa->data > pb->data) {
pc->next = pb;
pc = pb;
pb = pb->next;
}
else {//a==b,只插入其中之一
LinkList s = pb;
pc->next = pa;
pc = pa;
pa = pa->next;
pb = pb->next;
free(s);
}
}
pc->next = pa ? pa : pb;//插入剩余段
free(Lb);//释放Lb的头节点
}
参考资料: