顺序表(链式)
作者:互联网
顺序表(链式篇)
一、链式的理解
/*
链式存储的顺序表
把插入方式改为指定位置插入
也就是说直接找大于我这个键的第一次
然后直接中间插入
这边需要两个指针跑
*/
二、结构体
2.1 数据结构体
struct MM
{
char name[20];
int age;
};
2.2 添加键值结构体
struct Data
{
int index;
struct MM mmData;
};
2.3 节点
typedef struct Node
{
struct Data data;
struct Node* next;
}NODE,*LPNODE;
2.4 添加个数
typedef struct sqList
{
LPNODE headNode;
int sqListSize;
}SQL,*LPSQL;
三、封装节点与表头
3.1 创建节点
LPNODE createNode(struct Data data)
{
LPNODE newNode = (LPNODE)malloc(sizeof(NODE));
if (newNode == NULL)
{
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
3.2 创建表头
LPNODE createList()
{
LPNODE headNode = (LPNODE)malloc(sizeof(NODE));
if (headNode == NULL)
{
return NULL;
}
headNode->next = NULL;
return headNode;
}
四、封装整个表
LPSQL createSqList()
{
LPSQL sqList = (LPSQL)malloc(sizeof(SQL));
if (sqList == NULL)
{
return NULL;
}
sqList->headNode = createList();
sqList->sqListSize = 0;
return sqList;
}
五、插入数据
void insertData(LPSQL sqList, struct Data data)
{
LPNODE newNode = createNode(data);
//找指定位置
LPNODE leftPos = sqList->headNode;
LPNODE posNode = sqList->headNode->next;
//实现短路,不会出现NULL访问
while (posNode != NULL && posNode->data.index < data.index)
{
leftPos = posNode;
posNode = leftPos->next;
}
//有头链表所以这里插入不会有问题
leftPos->next = newNode;
newNode->next = posNode;
//链式必须插入成功
sqList->sqListSize++;
}
六、删除数据
void delete(LPSQL sqList,int index)
{
LPNODE leftNode = sqList->headNode->next;
LPNODE rightNode = sqList->headNode->next;
while (rightNode != NULL && rightNode->data.index!=index)
{
leftNode = rightNode;
rightNode = leftNode->next;
}
if (leftNode == NULL)
{
printf("此列表没有数据!无法删除!\n");
}
if (rightNode == NULL)
{
printf("此列表没有该人!无法删除!\n");
}
else
{
printf("删除成功!\n");
leftNode->next = rightNode->next;
free(rightNode);
rightNode=NULL;
sqList->sqListSize--;
}
}
七、打印
void printSqList(LPSQL sqList)
{
//顺序打印就完了!
LPNODE pMove = sqList->headNode->next;
while (pMove != NULL)
{
printf("%d:%s\t%d\n", pMove->data.index, pMove->data.mmData.name, pMove->data.mmData.age);
pMove = pMove->next;
}
}
八、主函数
int main(void)
{
srand((unsigned int)time(0));
LPSQL sqList = createSqList();
for (int i = 0; i < 3; i++)
{
struct Data data = { rand()%3,"wd",rand()%3 };
insertData(sqList, data);
}
printSqList(sqList);
delete(sqList, rand()%3);
printSqList(sqList);
return 0;
}
九、调试结果
9.1 没有找到
9.2 找到了并删除成功
标签:顺序,LPNODE,next,headNode,sqList,链式,NULL,data 来源: https://blog.csdn.net/weixin_50749712/article/details/113771450