1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| #include <stdio.h> #include <stdlib.h>
typedef struct Node { int data; struct Node* prev; struct Node* next; } Node;
Node* create_list() { Node* head = (Node*)malloc(sizeof(Node)); head->prev = head; head->next = head; return head; }
void append(Node* head, int data) { Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = data;
Node* last = head->prev; last->next = new_node; new_node->prev = last; new_node->next = head; head->prev = new_node; }
void prepend(Node* head, int data) { Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = data;
new_node->next = head->next; new_node->prev = head; head->next->prev = new_node; head->next = new_node; }
void delete_node(Node* head, int data) { Node* current = head->next; while (current != head) { if (current->data == data) { current->prev->next = current->next; current->next->prev = current->prev; free(current); return; } current = current->next; } printf("未找到值为%d的节点\n", data); }
int find_position(Node* head, int target) { Node* current = head->next; int position = 0;
while (current != head) { if (current->data == target) { return position; } current = current->next; position++; } return -1; }
int get_length(Node* head) { int count = 0; Node* current = head->next; while (current != head) { count++; current = current->next; } return count; }
void print_list(Node* head) { Node* current = head->next; printf("链表内容: "); while (current != head) { printf("%d ", current->data); current = current->next; } printf("\n"); }
void clear_list(Node* head) { Node* current = head->next; while (current != head) { Node* temp = current; current = current->next; free(temp); } head->next = head; head->prev = head; }
void destroy_list(Node* head) { clear_list(head); free(head); }
int main() { Node* head = create_list();
append(head, 10); append(head, 20); append(head, 30); prepend(head, 5);
print_list(head);
printf("元素20的位置: %d\n", find_position(head, 20)); printf("链表长度: %d\n", get_length(head));
delete_node(head, 20); print_list(head);
clear_list(head); destroy_list(head); return 0; }
|