#include <stdio.h>
//数组:地址是连续的 不易增删 不灵活
//链表:不连续 灵活
struct Test
{
int data;
struct Test *next;
};
void printlink(struct Test *head)//链表动态遍历
{
struct Test *point;
point = head;
while (point != NULL){
printf("%d ",point ->data);
point = point ->next;
}
putchar('\n');
}
int getNodesum(struct Test *head)//统计链表节点个数
{
int count = 0;
while(head != NULL){
count++;
head = head->next;
}
return count;
}
int searchNode(struct Test *head,int data)//查找指定的值是否在链表中
{
while(head !=NULL ){
if(head->data == data){
return 1;
}else{
head = head -> next;
}
}
return 0;
}
int insertNodebehind(struct Test *head,int data,struct Test *new)//从指定节点后方插入新节点
{
struct Test *point = head;
while(point != NULL){
if(point->data == data){
new->next = point->next;
point->next = new;
return 1;
}
point = point->next;
}
return 0;
}
struct Test *insertNodefront(struct Test *head,int data,struct Test *new2)//从指定节点前方插入新节点
{
struct Test *point = head;
if(point->data == data){
new2->next = head;
return new2;
}
while(point->next != NULL){
if(point->next->data == data){
new2->next = point->next;
point->next = new2;
printf("插入成功\n");
return head;
}
point = point->next;
}
printf("插入失败:no this data\n");
return head;
}
struct Test *reverseList(struct Test *head)//对链表进行逆向排序
{
struct Test *prve = NULL;// 指向前一个节点的指针,初始为 NULL
struct Test *current = head;// 指向当前节点的指针,初始为链表的头节点
struct Test *next = NULL; // 指向下一个节点的指针,初始为 NULL
while(current != NULL ){
next = current->next;
current->next = prve;
prve = current;
current = next;
}
return prve;
}
int main()
{
//链表的静态添加
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};
t1.next = &t2;
t2.next = &t3;
t3.next = &t4;
t4.next = &t5;
t5.next = &t6;
struct Test *head;
head = &t1;
struct Test new={100,NULL};//创建一个新节点,插入到指定节点的后方
printf("插入新节点100到指定节点的后面:\n");
int info;
info=insertNodebehind(head,6,&new);
if(info == 0){
printf("插入失败\n");
}else{
printf("插入成功\n");
}
printlink(head);//遍历插入后的链表
struct Test new2={101,NULL};//创建一个新节点new2,插入到指定节点的前方
printf("插入新节点101到指定节点的前面\n");
head = insertNodefront(head,1,&new2);
struct Test new3={106,NULL};//创建一个新节点new3,插入到指定节点的前方
printf("插入新节点106到指定节点的前面\n");
head = insertNodefront(head,5,&new3);
printlink(head);//遍历插入后的链表
int ret;
ret=getNodesum(head);//统计链表节点个数
printf("链表的节点个数=%d\n",ret);
int search;
search = searchNode(head,1);//查找指定的值是否在链表中
if(search == 0){
printf("no 1 in Node\n");
}else{
printf("have 1 in Node\n");
}
head = reverseList(head);//对链表进行逆向排序
printlink(head);//遍历逆向排序后的链表
return 0;
}```
demo9.7链表从指定节点前方插入新节点(附加逆向排序).c
最新推荐文章于 2025-12-05 14:37:41 发布
552

被折叠的 条评论
为什么被折叠?



