静态链表说明
使用数组来实现链式存储结构,目的是方便在不设指针类型的高级程序设计语言中使用链式结构
c语言定义数据结构
#define MAX_SIZE 1000
// 所有的类型都统一定义为ElemType
typedef int ElemType;
typedef struct
{
ElemType data;
int cur;
} component, LinkList[MAX_SIZE];
存储结构如下图所示
静态链表的工作原理
静态链表重点是在构建两个链表:备用链表(空闲的节点)和数据链表(已被使用的节点),下面来讨论一下两条链表是如何工作的
- 初始化链表,处标记颜色为空闲列表不可用时,其余所有的都属于备用链表(空闲的节点)
- 插入部分数据,静态链表同时产生备用链表(空闲的节点)和数据链表(已被使用的节点)
将上图结构分解一下,如下图
- 插入数据演示图
- 删除数据演示图
代码实现(A - B) U (B - A)
核心代码
void difference(LinkList &S1, int head)
{
ElemType temp, tail = head;
// A = { 1, 2, 3, 4, 5}, B = { 4, 5, 6, 7, 8}
int m = 5, n = 5;
// Build the first collection
for (int j = 1; j <= 5; j++)
{
temp = Malloc(S1);
S1[temp].data = j;
S1[tail].cur = temp;
tail = temp;
}
S1[tail].cur = 0;
printf("A = { ");
Traverse(S1, head, visit);
printf("}\n");
printf("B = { ");
// Adds the second collection to the first
for (int j = 4; j <= 8; j++)
{
printf("%d ", j);
// Find if an added element exists in the collection
int front = head, begin = S1[head].cur, end = S1[tail].cur;
while (begin != end && S1[begin].data != j)
{
front = begin;
begin = S1[begin].cur;
}
// Add element does not exist in the current collection, add to the collection
if (begin == end)
{
temp = Malloc(S1);
S1[temp].data = j;
S1[temp].cur = end;
S1[tail].cur = temp;
tail = temp;
}
else
{
// The element already exists in the collection, delete it
S1[front].cur = S1[begin].cur;
Free(S1, begin);
// Delete tail node, tail pointer needs to move forward one bit
if (begin == tail)
{
tail = front;
}
}
}
printf("}\n");
printf("(A - B) U (B - A) = { ");
Traverse(S1, head, visit);
printf("}\n");
}
int main()
{
LinkList S1;
Init(S1);
int head = Malloc(S1);
difference(S1, head);
return 0;
}
详细代码参考:所有代码入口
原文地址:https://www.cnblogs.com/dengjili/p/11731582.html
时间: 2024-10-13 16:49:22