#include #include
//结构体实现自定义
typedef structLNode{int elem;//代表数据域
struct LNode *next;//代表指针域,指向直接后继元素
}LNode, LinkList;//初始化链表//LNode * initLink();
LNode *initLink(){
LinkList* p = (LinkList*)malloc(sizeof(LNode));
LNode* temp = p; //声明一个指针指向头结点//生成链表
for(int i = 1; i < 5; i++){
LNode*a = (LNode*)malloc(sizeof(LNode));
a->elem =i;
a->next =NULL;
temp->next =a;
temp= temp->next;
}returnp;
}//*******************************************************//************插入函数***********************************//p是链表,elem是插入的结点的数据域,add是插入的位置
LNode * insertElem(LNode * p, int elem, intadd){
LNode* temp = p; //创建临时结点temp//首先找到要插入位置的上一个结点
for(int i = 1; i < add; i++) {if(temp ==NULL){
printf("插入位置无效");returnp;
}
temp= temp->next;
}//创建插入结点c
LNode * c = (LNode *)malloc(sizeof(LNode));
c->elem =elem;//向链表中插入结点
c->next = temp->next;
temp->next =c;returnp;
}//*******************************************************//************删除函数***********************************
LNode * delElem(LNode * p, intadd){
LNode* temp =p;//遍历到被删除结点的上一个结点
for(int i = 1; i < add; i++){
temp= temp->next;
}
LNode* del = temp->next;//单独设置一个指针指向被删除的结点//删除某个结点的方法就是更改前一个结点的指针域
temp->next = temp->next->next;free(del);//手动释放该结点,防止内存泄漏
returnp;
}//*******************************************************//************查找函数***********************************
int selectElem(LNode * p, intelem){
LNode* t =p;int i = 1;while(t->next){
t= t->next;if(t->elem ==elem){returni;
}
i++;
}return -1;
}//*******************************************************//************更改函数***********************************
LNode * updateElem(LNode * p, int add, intnewElem){
LNode* temp =p;
temp= temp->next;//temp指向首源结点//temp指向被删除的结点
for(int i = 1; i < add; i++){
temp= temp->next;
}
temp->elem =newElem;returnp;
}//void display(LNode *p);
void display(LNode *p){
LNode* temp = p; //将temp指针重新指向头结点//只要temp指针指向的结点的next不是Null,就执行输出语句
while(temp->next){
temp= temp->next;
printf("%d",temp->elem);
}
printf("");
}intmain(){
printf("初始化链表为:");
LinkList*p =initLink();
display(p);//插入函数
printf("在第四个位置插入元素5:");
p= insertElem(p, 5, 4);
display(p);//删除操作
printf("删除元素3:");
p= delElem(p, 3);
display(p);//查找操作
printf("查找元素2:");int address = selectElem(p, 2);if(address == -1){
printf("没有查到该元素");
}else{
printf("元素2的位置在:%d", address);
}//更改操作,将第三的位置改为数字999
printf("更改第三的位置数据为999:");
p= updateElem(p, 3, 999);
display(p);return 0;
}