假设结点的定义如下,请实现下面功能:
typedef struct node_s {
int data;
struct node_s* next;
} Node;
(a) 采用头插法,在链表中插入元素
void add_before_head(Node** plist, int val);
(b) 打印链表的所有结点的值。
void display_list(Node* list);
© 查找链表中第一个与指定值相等的结点,若没有这样的结点,则返回NULL。
Node* search_list(Node* list, int val);
(d) 写一个方法,释放链表中所有的结点。
void free_list(Node* list);
#include<stdio.h>
#include<stdlib.h>
typedef struct node_s {
int data;
struct node_s* next;
} Node;
//头插法
void add_before_head(Node** plist, int val) {
Node* newnode = malloc(sizeof(Node));
if (!newnode)
{
printf("error!");
exit(1);
}
newnode->data = val;
newnode->next = (*plist);
(*plist) = newnode;
}
void display_list(Node* list) {
if (!list)
{
printf("NULL!");
exit(1);
}
Node* p = list;
while (p != NULL)
{
printf("%d", p->data);
p = p->next;
}
}
Node* search_list(Node* list, int val) {
if (!list)
{
printf("NULL!");
exit(1);
}
Node* p = list;
while (p->data != val)
{
p = p->next;
}
return p;
}
void free_list(Node* list) {
Node* p;
p = list->next;
while (p != NULL)
{
list->next = p->next;
free(p);
p = list->next;
}
p = list;
free(p);
p = NULL;
}
//测试
int main() {
Node* head;
head = NULL;
add_before_head(&head, 1);
add_before_head(&head, 4);
add_before_head(&head, 3);
add_before_head(&head, 9);
printf("%d\n", search_list(head, 3)->data);
display_list(head);
free_list(head);
return 0;
}