//每个节点的前n-1个数据在数据域,最后一个数据在地址域
//每个链表必须有头指针,为指向结构体类型的指针
//数组与链表存储数据的区别:
//1、数组中的元素占用连续存储存储空间,链表不一定占用连续
//2、数组中数据元素访问随机,链表访问是顺序
//3、链表中插入和删除元素比数组操作效率高
// 建立链表:1、头插法(查到最前) 2、尾插法(插到最后)
//尾插法:
//1、malloc建立节点,让new指向它
//2、判断链表是否为空,如果为空,new指向它,否则找到最后
//3、加入节点
#include <stdio.h>
#include <stdlib.h>
struct student{
char name[16];
int score;
struct student *next;
};
struct student *head=NULL, *p, *t;
struct student* link_to_tail(int n)
{
head=NULL;
for (int i=1; i<=n; i++){
p=(struct student*)malloc(sizeof(struct student));
if (p==NULL) return NULL;
scanf("%s", p->name);
scanf("%d", &p->score);
p->next=NULL;
if (head==NULL){
head=p;
}else{
/*t=head;
while (t->next!=NULL){
t=t->next;
}
*/
t->next=p;
}
t=p;
}
return head;
}
struct student* link_to_head(int n)
{
head=NULL;
for (int i=1; i<=n; i++){
p=(struct student*)malloc(sizeof(struct student));
if (p==NULL) return NULL;
scanf("%s", p->name);
scanf("%d", &p->score);
p->next=head;
head=p;
}
return head;
}
void print()
{
if (head==NULL){
printf("empty list\n");
return;
}else{
t=head;
while (t!=NULL){
printf("%s %d\n", t->name, t->score);
t=t->next;
}
}
}
int get_len()
{
int len=1;
t=head;
while (t->next!=NULL){
len++;
t=t->next;
}
return len;
}
//i表示节点插入的位置(从1开始),考虑i不同值胡情况
//插入节点前,先调用求链表长度的函数,得到链表长度为n
struct student* insert_to_i(int i)
{
p=(struct student*)malloc(sizeof(struct student)) ;
if (p==NULL)
return NULL;
scanf("%s", p->name);
scanf("%d", &p->score);
p->next=NULL;
int len=get_len();
if (i<1 || i>len) return NULL;
else if (i==1){
p->next=head;
head=p;
}
else if (i<=len){
t=head;
for (int k=1; k<i-1; k++)
t=t->next;
p->next=t->next;
t->next=p;
}
return head;
}
//删除函数
//i表示节点删除的位置,考虑i的不同情况
struct student* delete_from_i(int i)
{
int len=get_len();
if (i<1 || i>len) return NULL;
else if (i==1){
head=head->next;
}else if (i<=len){
t=head;
for (int k=1; k<i-1; k++)
t=t->next;
t->next=t->next->next;
}
return head;
}
/*
struct student* listdelete(struct student* head, int i)
{
int j=1;
struct student *q, *p=head;
while (p!=NULL && j<i){
j++;
p=p->next;
}
if (p==NULL || j>i){
printf("error");
exit(0);
}
if (p==head){
head=head->next;
free(p);
}else{
q=p->next;
p->next=q->next;
free(q);
}
return head;
}
*/
int find(struct student* head, int x)
{
int index=1;
struct student* t=head;
while (t!=NULL){
if (t->score==x){
return index;
}
index++;
t=t->next;
}
return -1;
}
int main()
{
head=link_to_tail(5);
print();
int index;
scanf("%d", &index);
int ans=find(head, index);
if (ans!=-1)
printf("%d\n", ans);
else
printf("not found\n");
/*
head=insert_to_i(1);
print();
printf("%d\n", get_len());
head=insert_to_i(2);
print();
printf("%d\n", get_len());
int n;
scanf("%d", &n);
head=delete_from_i(n);
print();
printf("%d\n", get_len());
scanf("%d", &n);
head=delete_from_i(n);
print();
printf("%d\n", get_len());
*/
return 0;
}