#include "stdio.h"
#include <stdlib.h>
typedef struct Link{
float elem;
struct Link* next;
} link;
link* createLink(int size)
{
link* head = (link*)malloc(sizeof(link));
link* temp = head;
for(int i=1; i<size+1; i++){
link* a = (link*)malloc(sizeof(link));
a->elem = i*1.0;
a->next = NULL;
temp->next = a;
temp = a;
}
return head;
}
link* insertElem(link* p, int add, float val)
{
link* temp = p;
link* a = (link*)malloc(sizeof(link));
for(int i=1; i<add; i++){
if(temp->next == NULL){
printf("插入位置%d无效\n",add);
return p;
}
temp = temp->next;
}
a->elem = val;
a->next = temp->next;
temp->next = a;
return p;
}
link* delElem(link* p, int add)
{
link* temp = p;
if((!p)||(add<1)){
printf("输入参数无效\n");
return p;
}
for(int i=1; i<add; i++){
if(temp->next == NULL){
printf("删除位置%d无效\n",add);
return p;
}
temp = temp->next;
}
if(temp->next == NULL){
printf("删除位置%d无效\n",add);
return p;
}
link* delet = temp->next;
temp->next = temp->next->next;
free(delet);
delet = NULL;
return p;
}
int selectElem(link* p, float val)
{
if(!p)
return -1;
link* temp = p;
for(int i=0; temp->next;i++){
temp = temp->next;
if(temp->elem == val){
return i;
}
}
return -1;
}
link* amendElem(link* p, int add, float val)
{
if(!p)
return p;
link* temp = p;
for(int i=1; i<add; i++){
if(temp->next == NULL){
printf("修改位置%d无效\n",add);
return p;
}
temp = temp->next;
}
if(temp->next == NULL){
printf("修改位置%d无效\n",add);
return p;
}
temp->next->elem = val;
return p;
}
void display(void* prt)
{
link* temp = ((link*)prt)->next;
while(temp != NULL){
printf("%.1f ",temp->elem);
temp = temp->next;
}
}
void main()
{
int add = 0;
float val = 0.0;
printf("初始化链表为:\n");
link *p=createLink(5);
display(p);
add = 2; val = 1.5;
printf("在第%d号位置插入元素%.1f:\n",add, val);
p=insertElem(p, add, val);
display(p);
add = 4;
printf("删除%d号元素:\n",add);
p=delElem(p, add);
display(p);
val = 2.2;
add=selectElem(p, val);
if (add==-1) {
printf("没有查到元素值%.1f\n",val);
}else{
printf("元素值%.1f的位置为:%d\n",val,add);
}
add = 7; val = 1.8;
printf("更改第%d号位置的数据为%.1f:\n",add,val);
p=amendElem(p, add, val);
display(p);
system("pause");
return;
}