|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Cool_Breeze 于 2020-3-4 10:18 编辑
原文作者链接!
- #include <stdio.h>
- #include <malloc.h>
- #define SIZE sizeof(struct test)
- typedef struct test
- {
- int n;
- struct test *next;
- }*P;//定义P为(struct test *)的别名
- P initLink();//初始化链表
- void Display(P p);//打印链表元素
- P InsertElem(P p,int elem,int add); //插入节点
- P DeleteElem(P p,int position);//删除节点
- int FindElem(P p,int elem);//查找元素
- P change(P p,int data);//更改元素值
- //简单搜索指定元素的位置
- int location(P p,int element);
- int main()
- {
- //初始化链表
- P p=initLink();
- Display(p);
-
- printf("在8的位置插入元素88!\n");
- p=InsertElem(p,88,8);
- Display(p);
-
- printf("删除元素88\n");
- p=DeleteElem(p,8);
- Display(p);
-
- printf("查找元素6的位置\n");
- int position=FindElem(p,6);
- if (position < 0) printf("没有找到该元素\n");
- else printf("该元素的位置为:%d\n",position);
-
- printf("更该第四个元素的值为666!\n");
- p=change(p,666);
- Display(p);
-
- //简单搜索指定元素的位置
- int element=1;
- int locat=location(p,element);
- if (locat < 0) printf("没有找到该元素\n");
- else printf("元素值:%d的位置为:%d\n",element,locat);
-
- return 0;
- }
- P initLink()
- {
- P p=(P)malloc(SIZE);//头指针
- P temp = p;//指向头
- int i;
- for (i=1;i<=10;i++)
- {
- P a=(P)malloc(SIZE);//(首元节点)
- a->n=i;
- a->next=NULL;
- temp->next=a;
- temp=temp->next;
- }
- return p;
- }
- void Display(P p)
- {
- P temp = p;
- while (temp->next)//指向NULL时,代表结束
- {
- temp=temp->next;
- printf("%d ",temp->n);
- }
- putchar('\n');
- }
- P InsertElem(P p,int elem,int add)
- {
- P temp=p;
- //找到插入节点的上一个节点
- int i;
- for (i=1;i<add;i++)
- {
- if (! temp)//temp非空!
- {
- printf("插入位置ERROR!\n");
- return p;
- }
- temp=temp->next;
- }
- //创建插入节点A;
- P A=(P)malloc(SIZE);
- A->n=elem;//赋值
- A->next=temp->next;//指向下一个节点
- temp->next=A;//上一个节点指向A
- return p;
- }
- P DeleteElem(P p,int position)//删除节点
- {
- P temp=p;
- int i;
- for (i=1;i<position;i++)
- {
- temp=temp->next;
- }
- P pause=temp->next;//暂时储存被删除节点
- temp->next=temp->next->next;
- free(pause);//释放内存
- return p;
- }
- int FindElem(P p,int elem)
- {
- P temp=p;
- int i=1;
- while (temp->next)
- {
- temp=temp->next;
- if (temp->n == elem) return i;
- i++;
- }
- return -1;
- }
- P change(P p,int data)//更改元素值
- {
- P temp = p;//头指针(不是首元指针)
- int i=1;
- for (;i<=4;i++)
- {
- temp=temp->next;
- }
- temp->n=data;
- return p;
- }
- //简单搜索指定元素的位置
- int location(P p,int element)
- {
- P temp=p;
- int locat=1;
- while (temp->next)
- {
- temp=temp->next;
- if (temp->n == element) return locat;
- locat ++;
- }
- return -1;
- }
复制代码
|
|