Problem Description
链表结点的结构定义为:
struct node{
int value;
struct node *next;
};
编写下列函数:
void add_to_list(struct node **head, int n); //向链表首部插入一个值为n的结点
struct node *build_list(); //建立链表,调用函数add_to_list(struct node **head, int n)
struct node *search_list(struct node *head, int n); //搜索链表
void delete_from_list(struct node **head, int n); //删除链表中值为n的结点,并释放该结点
void print_list(struct node *head); //打印链表
测试程序为:
#include <stdio.h>
#include <stdlib.h>
struct node{
int value;
struct node *next;
};
void add_to_list(struct node **head, int n);
struct node *build_list();
struct node *search_list(struct node *head, int n);
void delete_from_list(struct node **head, int n);
void print_list(struct node *head);
int main()
{
struct node *first = NULL;
int n;
first = build_list();
print_list(first);
scanf("%d", &n);
if(search_list(first, n) == NULL)
{
printf("NO\n");
}
else
{
printf("YES\n");
}
delete_from_list(&first, n);
print_list(first);
return 0;
}
/* 你的代码将被嵌在这里 */
Input Description
输入的第一行是若干整数,为建立链表结点的值,当输入-1时结束。
输入的第二行是一个整数n,为搜索和删除的结点的值。
Output Description
第一行打印出链表结点的值,每个整数以","分隔,最后一个后面没有逗号。
第二行输出搜索值为n的结点的结果,找到了输出YES,否则输出NO。
第三行输出删除值为n的结点后的链表结点的值,每个整数以","分隔,最后一个后面没有逗号。
Sample Input
10 20 30 40 50 60 70 80 90 100 -1 60
Sample Output
100,90,80,70,60,50,40,30,20,10 YES 100,90,80,70,50,40,30,20,10
void add_to_list(struct node **head, int n)
{
struct node *new_node;
new_node = (struct node *) malloc(sizeof(struct node));
if(new_node == NULL)
{
exit(1);
}
new_node->value = n;
new_node->next = *head;
*head = new_node;
}
struct node *build_list()
{
struct node *first = NULL;
int m;
while(1)
{
scanf("%d", &m);
if(m == -1)
{
return first;
}
add_to_list(&first, m);
}
}
struct node *search_list(struct node *head, int n)
{
struct node *tmp;
for(tmp = head; tmp != NULL; tmp = tmp->next)
{
if(tmp->value == n)
{
return tmp;
}
}
return NULL;
}
void delete_from_list(struct node **head, int n)
{
struct node *cur;
struct node *pre;
struct node *tmp;
tmp = *head;
for(cur = *head, pre = NULL;cur != NULL && cur->value != n; pre = cur, cur = cur->next);
if(cur == NULL)
{
*head = tmp;
return;
}
if(pre == NULL)
{
*head = cur->next;
return;
}
else
{
pre->next = cur->next;
}
free(cur);
*head = tmp;
}
void print_list(struct node *head)
{
struct node *p;
for(p = head; p != NULL; p = p->next)
{
if(p == head)
{
printf("%d", p->value);
}
else
{
printf(",%d", p->value);
}
}
printf("\n");
}