//通过链表搜索下标index
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define max_op 5
typedef struct Node{
int value;
struct Node *next;
}Node;
Node *getnewNode(int val){
Node *p=(Node*)malloc(sizeof(Node));
p->next=NULL;
p->value=val;
return p;
}
int indexNode(Node *head,int val){
Node *p=head;//等于链表头部
int count=0;
while(p){
if(p->value==val){
return count;
}
p=p->next;
count++;
}
return -1;
}
void clear(Node *head){
if(head==NULL||head->next==NULL) return ;
for(Node *p=head,*q;p;p=q){
q=p->next;
free(p);
}
return ;
}
void insertNode(Node **head,int val){
Node *newnode=getnewNode(val);
if(*head==NULL){
*head=getnewNode(val);
return ;
}
Node *p=*head;
while(p->next){//p为NULL,p->next为前一个节点
p=p->next;
}
p->next=newnode;
return ;
}
//head->Node1->Node2->Node3->Node3
int main(void){
Node *head=NULL;
for(int i=0;i<max_op;i++){
insertNode(&head,i);
}
printf("index->%d ",indexNode(head,3));
clear(head);
return 0;
}