#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Node{
int data;
struct Node *next;
} Node;
typedef struct List{
int length;
Node *head;
} List;
List *init();
void clear(List *);
Node *new_node(int );
int insert(List *,int ,int );
int erase(List *,int );
void output(List *);
int main(){
srand(time(0));
List *list = init();
for(int i=0; i<20; ++i){
int val = rand() % 100; //随机插入值
int ind = rand() % (list->length +5) -2; //随机插入位置
int ope = rand() % 4; //随机操作类型
switch(ope){
case 0:
case 1:
case 2:
printf("insert[val:%d ind:%d] %d\n",val,ind,insert(list,val,ind)); //3/4的插入概率
break;
case 3:
printf("erase[ind:%d] %d\n",ind,erase(list,ind));//1/4的插入概率
break;
}
output(list); //输出链表所有值
printf("\n");
}
clear(list); //释放所有节点
return 0;
}
List *init(){ //初始化链表
List *res = (List *)calloc(1,sizeof(List));
res->head = new_node(0); //初始化头指针
res->head->next = NULL;
res->length = 0;
}
void clear(List *list){ //删除链表
if(list == NULL) return ;
Node *cur = list->head, *next;
while( cur ){
next = cur->next;
free( cur );
cur = next;
}
}
Node *nex_node(int val){ //创建新节点
Node *res = (Node *)calloc(1, sizeof(Node));
res->data = val;
res->next = NULL;
return res;
}
int insert(List *list, int val, int index){ //插入节点
if(list == NULL) return 0;
if(index<0 || index>list->length) return 0;
Node *cur = list->head;
while( index-- ){
cur = cur->next;
}
Node *temp = new_node(val);
temp->next = cur->next;
cur->next = temp;
++list->length;
return 1;
}
int erase(List *list, int index){ //删除节点
if(list == NULL) return 0;
if(index<0 || index>=list->length) return 0;
Node *cur = list->head;
while( index-- ){
cur = cur->next;
}
Node *temp = cur->next;
cur->next = temp->next;
free(temp);
--list->length;
return 1;
}
void output(List *list){
if(list == NULL || list->head == NULL) return ;
Node *cur = list->head->next;
printf("[");
while( cur ){
printf("%d->",cur->data);
cur = cur->next;
}
printf("NULL]\n");
}
c语言实现链表
最新推荐文章于 2024-07-12 16:27:59 发布