admin 管理员组

文章数量: 887021


2024年1月23日发(作者:框架网页怎么制作)

优先级反转代码

头文件

#include

#include

#include

//#define DEBUG //调试用

typedef struct node {

int priority; //优先级

int data; //数据

struct node *next;

} Node;

typedef struct node_list {

Node *head;

Node *tail;

int count; //链表中的元素数

} Node_list;

Node_list *init_list() {

- 1 -

Node_list *list = (Node_list*)malloc(sizeof(Node_list));

list->head = NULL;

list->tail = NULL;

list->count = 0;

return list;

}

void insert_node(Node_list *list, int data) {

if (list == NULL) return ;

//在链表末尾插入新元素

Node *p = (Node*)malloc(sizeof(Node));

p->priority = 0;

p->data = data;//数据域初始化

p->next = NULL;

if (list->head == NULL) {

list->head = p;

list->tail = p;

list->count = 1;

} else {

//将新元素插入到链表末尾

list->tail->next = p;

- 2 -

list->tail = p;

list->count++;

}

return ;

}

void delete_node(Node_list *list, int data) {

Node *p = list->head;

while (p) {

if (p->data == data) {

//找到了需要删除的节点

//如果不是头结点, 那么更改前一个节点的next指针即可

if (p != list->head) {

Node *q = list->head;

while (q->next != p) {

q = q->next;

}

q->next = p->next;

} else {

list->head = list->head->next;

}

//如果删除的是尾节点, 那么更改尾节点的位置

- 3 -

if (p == list->tail) {

list->tail = q;

}

free(p);

list->count--;

return ;

}

p = p->next;

}

return ;

}

void search_node(Node_list *list, int data) {

Node *p = list->head;

while (p) {

if (p->data == data) {

printf('node is found!

');

return ;

}

p = p->next;

- 4 -

}

printf('node is not found!

');

return ;

}

//修改节点优先级

void reverse_node_priority(Node_list *list, int data) {

Node *p = list->head;

while (p) {

if (p->data == data) {

p->priority++;

return ;

}

p = p->next;

}

printf('node is not found!

');

return ;

}

//打印链表

- 5 -

void output_list(Node_list *list) {

Node *p = list->head;

while (p) {

printf('node: %d, priority: %d

', p->data, p->priority);

p = p->next;

}

return ;

}

void clear_list(Node_list *list) {

Node *p = list->head;

while (p) {

Node *q = p->next;

free(p);

p = q;

}

free(list);

return ;

}

int main() {

- 6 -

#ifdef DEBUG

Node_list *list = init_list();

insert_node(list, 1);

insert_node(list, 2);

insert_node(list, 3);

output_list(list);

printf('reverse priority

');

reverse_node_priority(list, 3);

reverse_node_priority(list, 2);

output_list(list);

delete_node(list, 2);

output_list(list);

clear_list(list);

#endif

return 0;

}。

- 7 -


本文标签: 节点 链表 更改 删除 末尾