#include<stdio.h>
#include<stdlib.h>
typedef int Item;
typedef struct node
{
Item data;
struct node *next;
}Node;
Node *first = NULL;
static void terminate(const char *message)
{
printf("%s\n", message);
exit(EXIT_FAILURE);
}
//在链表开始处插入结点
void add_to_list(Item x)
{
Node *new_node;
new_node = (Node *)malloc(sizeof(Node));
if (new_node == NULL)
terminate("Error: malloc failed in add_to list!");
new_node->data = x;
new_node->next = first;
first=new_node;
}
void delete_element(Item x) {
Node *prev, *cur;
for (cur = first, prev = NULL;
cur != NULL && cur->data != x;
prev = cur, cur = cur->next);
if (cur == NULL)
printf("data was not found!");
if (prev == NULL)
first = first->next;
else
{
prev->next = cur->next;
free(cur);
}
}
void select_list(Item x) {
Node *p;
for (p = first; p != NULL && p->data != x; p = p->next);
if (p == NULL)
printf("Don't find node!");
else
printf("find node!");
}
void print_list()
{
Node *p;
for (p = first; p != NULL; p = p->next) {
printf(" %d ", p->data);
}
}
C/C++ 单链表
最新推荐文章于 2025-02-23 21:00:35 发布