C# · 12月 20, 2021

C/C++ 单链表

#include

#include

typedef int Item;

typedef struct node

{

Item data;

struct node *next;

}Node;

Node *first = NULL;

static void terminate(const char *message)

{

printf(“%sn”,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);

}

}