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");
}
c语言实现链表
最新推荐文章于 2024-10-18 11:06:32 发布