标准C程序设计-链表2

20 篇文章 0 订阅
本文介绍如何使用C语言编写函数,实现链表中数据项的插入和删除操作,包括在指定节点前插入数据以及删除指定节点。
摘要由CSDN通过智能技术生成

        题目:编写函数,把给定数据项插入到指定节点之前,然后删除。

        本程序涉及到连标的基本操作:遍历链表、插入一个数据项、删除一个数据项。

/*插入关键节点之前*/
node *insert(node *head)
{
	node *new_node;
	node *find_node;
	int key;
	int x;

	printf("Value of new_node item?\n");
	scanf("%d", &x);
	printf("Value of key item?(type -999 if last\n");
	scanf("%d", &key);
    /*新节点是第一项*/
	if (head->key == key)
	{
		new_node = (node *) malloc(sizeof(node));
		new_node->key = x;
		new_node->next = head;
		head = new_node; 
	}
	else
	{
		find_node = find(head, key);
		if (find_node == NULL)
		{
			printf("KEY is not found.\n");
		}
		new_node->key = x;
		new_node->next = find_node->next;
		find_node->next = new_node;
	}
    
    return (head);
}
/*返回关键字的前一个节点*/
node *find(node *list, int key)
{
	if (list->next->key == key)
	{
		return (list);
	}
	else
		if (list->next->next == NULL)
		{
			return (NULL);
		}
	else
    {
		find(list->next, key);
	}
}
/*删除指定节点*/
node *delete_node(node *head)
{
	int key;
	node *find_node;
	node *p;
	printf("What is the item (key) to be deleted?\n");
	scanf("%d", &key);
	if (head->key == key)
	{
		head = head->next;
		free(head);
	}
	else
	{
		find_node = find(head, key);
		if (find_node == NULL)
		{
			printf("key not found!\n");
		}
		else
		{
			p = find_node->next->next;
			find_node->next = p;
			free(p);
		}
	}
	return (head);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值