这个是链表的向链表元素前方插入(前插法)和向链表元素后方插入(后插法)和指定删除某个链表元素,指定修改某个元素的代码,也是非常的爽,花了我n个小时才理解所有的方法。。。因人而异但是真的是很不错的例题。
代码在这
#include <stdio.h>
struct Test
{
int data;
struct Test *next;
};
void printfInfo(struct Test *head)
{
struct Test *point;
point = head;
while(point !=NULL){
printf("%d ",point->data);
point =point->next;
}
putchar('\n');
}
int printfInfo1(struct Test *head,int data)
{
int count = 0;
int found = 0;
struct Test *point;
point = head;
while(point !=NULL){
count++;
if((point->data) == data){
found=1;
}
point = point->next;
}
if(found==1){
printf("have\n");
}else{
printf("no\n");
}
return count;
}
struct Test * gaiNum(struct Test *head,int data,int newdata)
{
struct Test *p;
p = head;
while(p !=NULL){
if(p->data == data){
p->data=newdata;
}
p = p->next;
}
return head;
}
struct Test *insertBehindNum(struct Test *head,int data,struct Test *new)
{
struct Test *p;
p=head;
while(p != NULL){
if(p->data == data){
new->next= p->next;
p->next = new;
return head;
}
p = p->next;
}
return head;
}
struct Test *insertbeforeNum(struct Test *head,int data,struct Test *new)
{
struct Test *p;
p=head;
if(p->data == data){
new->next=p;
printf("insert ok\n");
return new;
}
while(p->next != NULL){
if(p->next->data==data){
new->next = p->next;
p->next = new;
printf("insert ok\n");
return head;
}
p = p->next;
}
return head;
}
struct Test *deleteNum(struct Test *head,int data)
{
struct Test *p;
p=head;
if(p->data == data){
p=p->next;
printf("delete ok\n");
return head;
}
while(p->next != NULL){
if(p->next->data == data){
p->next = p->next->next;
printf("delete ok~\n");
return head;
}
p = p->next;
}
return head;
}
int main()
{
int count;
struct Test *head = NULL;
struct Test t1={1,NULL};
struct Test t2={2,NULL};
struct Test t3={3,NULL};
struct Test t4={4,NULL};
struct Test new={100,NULL};
struct Test new2={999,NULL};
struct Test new3={888,NULL};
t1.next=&t2;
t2.next=&t3;
t3.next=&t4;
printfInfo(&t1);
count = printfInfo1(&t1,4);//查
printf("链表元素个数为%d\n",count);
head=insertBehindNum(&t1,3,&new);//在后方插入
printfInfo(head);
head = insertbeforeNum(&t1,3,&new2);//在前方插入
printfInfo(head);
head = insertbeforeNum(&t1,1,&new3);//在前方插入
printfInfo(head);
head = deleteNum(&t1,1);//删除
printfInfo(head);
head = gaiNum(&t1,1,40);//改
printfInfo(head);
return 0;
}
我在这边放一下适于理解的图,以及便于理解链表的前插法
--------------------------------------------------------------------------------------------------------------------------------
我在这边放一下适于理解的图,以及便于理解链表的后插法
请注意这里有些不同看起来后插入的图和前插入的第二种情况很相似,但是是不一样的因为他们的data不一样,也就是表达的意思是不一样的,一个是data=3的时候前插入,一个是data=2的时候后插入。
其中最重要的代码是:
前插入函数的设计部分:
if(p->next->data==data){}这边我想说的是一定要理解if里面的表达式p->next->data==data是什么意思 意思就是 当前p的下一个p表示的的data会等于你传过来的data,这样我们才能说找到你想要在那个数前面插入新链表;
后插法的设计部分:
while(p != NULL)只要当前这个指针是存在的(不为空)那么就可以在这个指针后面插入,只要 p
不为 NULL
,就继续循环。
删除和修改的函数相信大家都能理解。
代码中有很多小细节:
比如 struct Test *p;
p=head;
这个完全是一个好的编码习惯,也符合逻辑,也适合给每一个人看,不然显得很突兀,因为容易被理解为怎么可能链表遍历下去了一直是head,head表示头部的意思,容易被误导。