c语言实现链表

#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");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值