main.c
#include <myhead.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "link.h"
int main(int argc, const char *argv[])
{
plink l = create();
front_insert(l);
output_link(l);
anypos_insert(l);
output_link(l);
anypos_dele(l);
output_link(l);
reve_link(l);
output_link(l);
return 0;
}
link.c
#include <myhead.h>
#include "link.h"
plink create(){
plink p = malloc(sizeof(liink));//创建头节点
if(p==NULL){
printf("创建失败\n");
return NULL;
}
printf("创建成功\n");
p->len=0;
p->next = NULL;
return p;
}
int front_insert(plink l){
if(l==NULL){
printf("失败");
return -1;
}
plink p = create();
printf("请输入学号:");
scanf("%d",&p->s.id);
printf("请输入姓名:");
scanf("%s",p->s.name);
printf("请输入成绩:");
scanf("%f",&p->s.score);
p->next = l->next;
l->next = p;
l->len++;
return 0;
}
int output_link(plink l){
if(l==NULL){
printf("输出失败");
return -1;
}
plink t = l;
for(int i=0;i<l->len;i++){
t = t->next;
printf("学号:%d 姓名:%s 成绩:%f",t->s.id,t->s.name,t->s.score);
}
printf("\n");
return 0;
}
int anypos_insert(plink l){
int pos;
printf("请输入要插入的位置:");
scanf("%d",&pos);
if(l==NULL||pos<1||pos>l->len+1){
printf("插入失败");
return -1;
}
plink p = create();
printf("请输入学号:");
scanf("%d",&p->s.id);
printf("请输入姓名:");
scanf("%s",p->s.name);
printf("请输入成绩:");
scanf("%f",&p->s.score);
plink t = l;
for(int i=0;i<pos-1;i++){
t = t->next;
}
p->next = t->next;
t->next = p;
l->len++;
return 0;
}
int anypos_dele(plink l){
int pos=3;
if(l==NULL||l->len==0||pos<1||pos>l->len){
printf("删除失败");
return -1;
}
plink t = l;
for(int i=0;i<pos-1;i++){
t = t->next;
}
plink Q = t->next;
t->next = t->next->next;
free(Q);
l->len--;
return 0;
}
int reve_link(plink l){
plink Q,t;
l->next = Q;
Q->next = t;
while(t!=NULL){
Q->next = t->next;
l->next = t;
t->next = l->next;
t = Q->next;
}
return 0;
}
link.h
#ifndef _LINK_H_
#define _LINK_H_
typedef struct{
int id;
char name[20];
float score;
}stu,*sstu;
typedef struct node{
union{
int len;
stu s;
};
struct node *next;
}liink,*plink;
plink create();
int front_insert(plink);
int output_link(plink);
int anypos_insert(plink);
int anypos_dele(plink);
int reve_link(plink);
#endif