结构设计
就像动态数组一样,我们创建一个结构体来代表整个链表,记录链表长度,我们就可以在指定位置插入或者查找元素。整表结构体需要记录头结点地址和链表长度。
typedef struct {
void* data;
LinkNode* next;
} LinkNode;
typedef struct {
LinkNode pHeader;
int size;
} LList;
typedef void* LinkList;
代码
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
typedef struct LinkNode {
int data;
struct LinkNode* next;
} LinkNode;
typedef struct LinkNode * LinkList;
LinkList init();
void travel(LinkList);
int size(LinkList);
void insert(LinkList, int, int);
int main()
{
LinkList linkList = init();
travel(linkList);
insert(linkList, 10, 100);
travel(linkList);
return 0;
}
LinkList init() {
LinkList linkList = (LinkList)malloc(sizeof(LinkNode));
LinkNode* linkTailNode = NULL;
if (linkList == NULL) {
return NULL;
}
linkList->data = 0;
linkList->next = NULL;
linkTailNode = linkList;
int val = -1;
while (1) {
printf("插入数据\n");
scanf("%d", &val);
if (val == 0) {
break;
}
LinkNode * linkNode = (LinkNode*)malloc(sizeof(LinkNode));
linkNode->data = val;
linkNode->next = NULL;
linkTailNode->next = linkNode;
linkTailNode = linkNode;
linkList->data += 1;
}
return linkList;
}
void travel(const LinkList const linkList) {
LinkNode* currentNode = linkList->next;
while (currentNode != NULL) {
printf("%d,", currentNode->data);
currentNode = currentNode->next;
}
}
int size(const LinkList const linkList) {
printf("%d", linkList->data);
return linkList->data;
}
void insert(LinkList linkList, int oldVal, int newVal) {
if (linkList == NULL)
{
return;
}
LinkNode *preNode = linkList;
LinkNode *curNode = linkList->next;
while(curNode != NULL) {
if (curNode->data == oldVal)
{
break;
}
preNode = curNode;
curNode = curNode->next;
if (curNode == NULL)
{
return;
}
}
LinkNode* newNode = (LinkNode*)malloc(sizeof(LinkNode));
newNode->data = newVal;
newNode->next = NULL;
preNode->next = newNode;
newNode->next = curNode;
linkList->data += 1;
}
void destory(LinkList* linkList) {
LinkNode* currentNode = (*linkList)->next;
while (currentNode != NULL)
{
LinkNode* nextNode = currentNode->next;
free(currentNode);
currentNode = nextNode;
}
(*linkList)->next = NULL;
*linkList = NULL;
}
函数名 函数名取地址 区别
C的结构体报错