题目:编写函数,把给定数据项插入到指定节点之前,然后删除。
本程序涉及到连标的基本操作:遍历链表、插入一个数据项、删除一个数据项。
/*插入关键节点之前*/
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);
}