c语言实现链表

typedef struct Light{
	  //成员
      int   value;          //传入的值  <0代表没有值传入
	  struct Light *next;  
};

//tail.next = NULL;
//head.next =&tail;

Light* light_init(){
	Light *head=(Light *)malloc(sizeof(Light));
	if(head == NULL){
		return NULL;
	}
	head->next = NULL;
	head->value = -1;
	return head;
}
//插入链表中
void inerst(int value,Light *head){
	Light *p=(Light*)malloc(sizeof(Light));
	if(p == NULL){
		return ;
	}
	p->value = value;
	p->next = NULL;
	if(head->next == NULL){//头为空
		head->next=p;
	}else{//非空
		p->next = head->next;
		head->next = p;
	}
}
//链表销毁成员
void destory(int value,Light *head){
	if(head->next == NULL){//没有元素
		return;
	}
	Light *pf = head;
	Light *ps = head->next;
	while(ps != NULL){
		if(ps->value == value){
			pf ->next = ps->next;
			free(ps);
			ps = pf->next;
		}else{
			pf = ps;
			ps = ps->next;
		}
	}
}
//链表长度
int length(Light *head){
	Light *p = head;
	int length = 0;
	while(p->next != NULL){
		p = p->next;
		length++;
	}
	return length;
}
//查找到对应的值之后回调pfunction
void find(int value,Light *head,void (*pfuntion)(int) ){
	Light *p = head;
	while(p->next != NULL){
		p = p->next;
		if(p->value == value){
			pfuntion(p->value);
			break;
		}
	}
}
//遍历链表
void traverse(Light *head,void(*pfunction)(int)){
	Light *p = head;
	while(p->next != NULL){
		p = p->next;
		pfunction(p->value);
	}
}

//清空所有的值
void clear(Light *head,void (*pfunction)(int)){
	if(head->next == NULL){
		return;
	}
	while(head->next != NULL){
		Light *n = head->next;
		pfunction(n->value);
		if(n->next == NULL){
			free(n);
			break;
		}
		head->next = n->next;
		free(n);
	}
	head->next = NULL;
}


int main(){
	cout<<"hello world"<<endl;
	struct Light * head = light_init();
	//插入元素
	for(int i = 0;i < 6 ; i++){
		int data1 = 0;
		cin>>data1;
		inerst(data1,head);		
	}
	cout<<"链表长度length="<<length(head)<<endl;
	cout<<"销毁输入的元素"<<endl;
	int data2 = 0;
	cin>>data2;
	destory(data2,head);
	cout<<"链表长度length="<<length(head)<<endl;
	cout<<"遍历"<<endl;
	traverse(head,on);//遍历
	int data3 = 0;
	cout<<"find"<<endl;
    cin>>data3;
	find(data3,head,on);
	cout<<"链表长度"<<endl;
	clear(head,on);
	cout<<"链表长度length="<<length(head)<<endl;

	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值