#include<stdio.h>
#include<malloc.h>
//线性链表上的结点类型
typedef struct node{
int key;
struct node* next;//指向下一个结点
}LNode;
typedef LNode* SQLIST;//链表类型
//构造链表
SQLIST createlist(SQLIST L ,int k){
LNode* flag = NULL;
if(L == NULL){//链表为空
if((L = (LNode*)malloc(sizeof(LNode))) == NULL){
printf("不能分配内存");
}
flag = L;
flag->next = NULL;
flag->key = k;
}
else{
flag = L;
while((flag->next) != NULL){
flag = flag->next;
}
if((flag->next = (LNode*)malloc(sizeof(LNode))) == NULL){
printf("不能分配内存");
}
flag->next->key = k;
flag->next->next = NULL;
flag = flag->next;
}
return L;
}
//查找指定结点,返回匹配结点的位置
int SqSearch(SQLIST L,int aidkey){
int flag = -1;
int count = 1;//初始化为链表的第一个结点标号
LNode* index = L;//指向链表头
while(index != NULL){
if(index->key == aidkey){
flag = count;
}
index = index->next;
count++;
}
return flag;
}
void main(){
SQLIST sq = NULL, head = NULL;
printf("----------create list---------------\n");
for(int i = 0 ; i < 100; i++){
sq = createlist(sq,i+1);
}
head = sq;
//打印链表结点值
for(int j = 0 ; j < 100; j++){
printf("%d ",head->key);
if(j%5 == 0)
printf("\n");
head = head->next;
}
printf("\n----------search list---------------\n");
int flag = SqSearch(sq,50);
printf("所在位置为第 %d 个结点\n",flag);
}