在C语言中,链表是一种常见的数据结构,用于存储一系列的元素,这些元素在内存中并不一定是连续存储的。每个元素包含了数据本身以及指向列表中下一个元素的指针。在链表中从指定节点后插入新节点是链表操作中的基本操作之一。 前面提到了链表与数组的区别,接下来在这串代码的基础上了解,在链表指定节点前后插入的区别。
一、链表从指定节点后插入
int insert(struct Test *head,int data,struct Test *New){
while(head != NULL){//判断最后一个节点是否为空,空的就结束循环
if(head->data == data){
New->next = head->next;
head->next = New;
return 1;
}
head = head->next;
}
return 0;
二、链表从指定节点前插入
比较下面这段代码:
struct Test* Insertfor(struct Test *head, int data, struct Test *new){
struct Test *p = head;
if(p->data == data){ //首先判断是否是在表头插入,如果是直接替换表头
new->next = p;
return new;
}
while(p->next != NULL){//判断最后一个节点是否为空,空的就结束循环
if(p->next->data == data){
new->next = p->next;
p->next = new;
return head;
}
p = p->next;
}
return head;
}
这是一段前插入的代码,前插入可以分为两中情况,在表头插入,替代表头成为表头。
三、完整代码案例
下面是我自己写的完整代码:
#include <stdio.h>
struct Test{
int data;
struct Test *next;
};
void printlink(struct Test *head){
while(head != NULL){
printf("%d ",head->data);
head = head->next;
}
putchar('\n');
}
int insert(struct Test *head,int data,struct Test *New){
while(head != NULL){
if(head->data == data){
New->next = head->next;
head->next = New;
return 1;
}
head = head->next;
}
return 0;
}
struct Test* Insertfor(struct Test *head, int data, struct Test *new){
struct Test *p = head;
if(p->data == data){
new->next = p;
return new;
}
while(p->next != NULL){
if(p->next->data == data){
new->next = p->next;
p->next = new;
return head;
}
p = p->next;
}
return head;
}
int main (){
int i ;
int arr[]= {1,2,3};
for(i=0;i<sizeof(arr)/sizeof(arr[0]);i++){
printf("%d ",arr[i]);
}
putchar('\n');
struct Test t1 = {1,NULL};
struct Test t2 = {2,NULL};
struct Test t3 = {3,NULL};
struct Test t4 = {4,NULL};
struct Test t5 = {5,NULL};
struct Test t6 = {6,NULL};
struct Test t7 = {7,NULL};
struct Test t8 = {8,NULL};
struct Test t100 = {100,NULL};
struct Test t101 = {110,NULL};
t1.next = &t2;
t2.next = &t3;
t3.next = &t4;
t4.next = &t5;
t5.next = &t6;
t6.next = &t7;
t7.next = &t8;
printf("use t1 to print other four nums:\n");
//printf("%d %d %d %d",t1.data,t1.next->data,t1.next->next->data,t1.next->next->next->data);
puts("after insert:");
insert(&t1,3,&t100);
printlink(&t1);
struct Test* head;
head = Insertfor(&t1,5,&t101);
printlink(head);
return 0;
好了,以上就是今天的学习内容。