在链表指定数据odata前插入ndata数据,如果在链表中找不到此数据,则在结尾插入

在指定数据odata前插入ndata数据,如果在链表中找不到此数据,则在结尾插入

struct student 
{
	int age;
	struct student* next;
};
//打印链表
void myprint(struct student* head)
{
	struct student* p = head->next;
	while (p != NULL)
	{
		printf("%d     ", p->age);
		p = p->next;
	}
}
//初始化学生链表,在age输入-1时结束
struct student* initStudent()
{
	struct student* head;
	head = malloc(sizeof(struct student));
	head->next = NULL;
	struct student* tail;
	tail = head;
	int val = -1;
	while (1)
	{
		scanf("%d", &val);
		if (val == -1)
		{
			break;
		}
		struct student* new = malloc(sizeof(struct student));
		new->next = NULL;

		new->age = val;
		tail->next = new;
		tail = new;
	}
	return head;
}
//在指定数据odata前插入ndata数据,如果在链表中找不到此数据,则在结尾插入
void insert(struct student *head,int odata,int ndata)
{
	struct student* new = malloc(sizeof(struct student));
	new->age = ndata;
	new->next = NULL;
	struct student* p = head;
	while (p->next!=NULL)
	{
		if (p->next->age==odata)
		{
			new->next = p->next;
			p->next = new;
			return;
		}
		p=p->next;
	}
	p->next = new;

}
void test()
{
	struct student* head= initStudent();
	insert(head,20,1000);
	insert(head,20,2000);
	insert(head,-1,500);
	insert(head,30,3000);
	myprint(head);
}
int main(void)
{
	test();

	system("pause");
	return EXIT_SUCCESS;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值