循环双链表的拆分 满足用递归的形式实现链表的销毁,只出现一次free,用户可自行选择前插或后插法
时间: 2024-04-29 18:23:56 浏览: 14
以下是使用递归实现循环双链表拆分并销毁的代码,其中用户可以选择前插或后插法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* prev;
struct node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
void insertNode(Node** head, int data, int insertType) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
(*head)->prev = *head;
(*head)->next = *head;
return;
}
if (insertType == 0) { // 前插法
newNode->prev = (*head)->prev;
newNode->next = *head;
(*head)->prev->next = newNode;
(*head)->prev = newNode;
*head = newNode;
} else { // 后插法
newNode->prev = (*head)->prev;
newNode->next = (*head)->prev->next;
(*head)->prev->next = newNode;
(*head)->prev = newNode;
}
}
void splitList(Node* head, Node** list1, Node** list2, int splitValue) {
if (head == NULL) {
return;
}
if (head->data <= splitValue) {
insertNode(list1, head->data, 1); // 后插法插入到list1
} else {
insertNode(list2, head->data, 0); // 前插法插入到list2
}
splitList(head->next, list1, list2, splitValue);
free(head);
}
void printList(Node* head) {
if (head == NULL) {
printf("NULL\n");
return;
}
Node* current = head;
do {
printf("%d <-> ", current->data);
current = current->next;
} while (current != head);
printf("Head\n");
}
int main() {
Node* head = NULL;
insertNode(&head, 8, 0);
insertNode(&head, 6, 0);
insertNode(&head, 7, 0);
insertNode(&head, 5, 0);
insertNode(&head, 4, 0);
insertNode(&head, 3, 0);
insertNode(&head, 2, 0);
insertNode(&head, 1, 0);
printf("Original list:\n");
printList(head);
Node* list1 = NULL;
Node* list2 = NULL;
splitList(head, &list1, &list2, 5);
printf("List1:\n");
printList(list1);
printf("List2:\n");
printList(list2);
return 0;
}
```
在上面的代码中,`insertNode`函数用于在循环双链表中插入新节点。`splitList`函数用于实现循环双链表的拆分,并将较小或等于拆分值的节点插入到`list1`中,将较大的节点插入到`list2`中。`printList`函数用于打印循环双链表。在主函数中,我们先创建一个循环双链表,然后调用`splitList`函数进行拆分。最后打印拆分后的两个链表。