更多资料请点击:我的目录
本篇仅用于记录自己所学知识及应用,代码仍可优化,仅供参考,如果发现有错误的地方,尽管留言于我,谢谢!

此篇是单向链表实现增删改查的操作,其中:
"增"包括在链尾、链中增加节点
"删"包括在链头、链中、链尾删除单个或多个节点
"改"包括在链头、链中、链尾更改单个或多个节点数值
"查"只是显示整个链表所有节点数值

#include <stdio.h>
#include <stdlib.h>

//设计节点
struct node																
{
	int data;
	struct node *next;
};

//链表初始化
struct node *list_init()
{
	struct node *head = malloc(sizeof (struct node));
	head->next = NULL;
	return head;
}

//创建新节点
struct node *newnode(int data)
{
	struct node *new = malloc(sizeof(struct node));
	new->data = data;
	new->next = NULL;
	
}

//链尾加入节点
int addtail(int newdata , struct node *list)
{
	struct node *p = list;
	while(p->next != NULL)
	{
		p = p->next;
	}
	struct node *new = newnode(newdata);
	p->next = new;
}

//链中插入节点
int insert(int olddata,int newdata,struct node *list)
{
	int b = 0;//判断标志
	struct node *p = list;
	while(p->next != NULL)
	{
		if(p->data == olddata)
		{
			struct node *new = newnode(newdata);
			new->next = p->next;
			p->next = new;
			b = 1;

			//当新旧节点数据相等时,跳过新节点,防止进入无限循环
			if(olddata == newdata)
			{
				p = p->next;
			}
		}
		p = p->next;
	}
	
	//链尾加入节点
	if(p->next == NULL && p->data == olddata)		
	{
		struct node *new = newnode(newdata);
		p->next = new;
		b = 1;
	}
		printf("\n=====在链表%d后加入节点%d=====\n",olddata,newdata);
	if(b == 0)
		printf("原链表节点没有%d这个数值!\n",olddata);
	
}

//删除节点
int delnode(int deldata,struct node *list)
{
	int b = 0, m = 0;//判断标志
	struct node *q = list;
	struct node *p = list->next;
	
	printf("\n=====删除节点%d=====\n",deldata);
	while(p != NULL)
	{
		if(p->data == deldata)
		{
			q->next = p->next;
			p->next = NULL;
			free(p);
			b = 1;
			m = 1;
		}

		if(m == 1)
		{
			p = q->next;
			m = 0;
		}

		else
		{
			p = p->next;
			q = q->next;
		}
	}
	if(b == 0)
		printf("原链表节点没有%d这个数值!\n",deldata);
		
}


//更改节点数值
int change(int olddata, int newdata, struct node *list)
{
	int b = 0;
	struct node *p = list->next;
	while(p != NULL)
	{
		if(p->data == olddata)
		{
			p->data = newdata;
			b = 1;
		}
		p = p->next;
	}
		printf("\n=====更改节点%d为%d=====\n",olddata,newdata);
	if(b == 0)
		printf("原链表节点没有%d这个数值!\n",olddata);
}

//显示所有节点
int show(struct node *list)
{
	printf("链表各节点:\t");
	struct node *p = list->next;
	{
		while(p != NULL)
		{
			printf("%d\t",p->data);
			p  = p->next;
		}
		printf("\n");
	}
	
}

int main(int argc, char **argv)
{
	struct node *list = list_init();

	addtail(350,list);
	addtail(100,list);
	addtail(200,list);
	addtail(200,list);
	addtail(250,list);
	addtail(800,list);
	addtail(200,list);
	addtail(100,list);
	show(list);

	insert(100,150,list);
	show(list);
	
	delnode(200,list);
	show(list);
	
	delnode(150,list);
	show(list);
	
	delnode(350,list);
	show(list);
	
	change(250,500,list);
	show(list);
	
	insert(700,150,list);
	show(list);
	
	delnode(700,list);
	show(list);
	
	change(700,150,list);
	show(list);
	
	return 0;
}

运行结果:
在这里插入图片描述

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐