假设一个单循环链表,其结点含有三个域pre、data、link。其中data为数据域;pre为指针域,它的值为空指针(NIL);link为指针域,它指向后继结点。请设计算法,将此表改成双向循环链表。 使用C语言写出完整代码
时间: 2024-05-12 07:16:17 浏览: 41
已知单链表L为按值递增有序的,编写算法将数据元素值在区间[e1,e2]内的所有结点取出建立一个新单链表L1
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* pre;
struct Node* link;
} Node;
void AddNode(Node** head, int data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->pre = NULL;
new_node->link = NULL;
if (*head == NULL) {
*head = new_node;
new_node->link = *head;
new_node->pre = *head;
} else {
Node* temp = *head;
while (temp->link != *head) {
temp = temp->link;
}
temp->link = new_node;
new_node->pre = temp;
new_node->link = *head;
(*head)->pre = new_node;
}
}
void ConvertToDoubleLinkedList(Node** head) {
Node* temp = *head;
Node* prev = NULL;
while (temp != NULL) {
temp->pre = prev;
prev = temp;
temp = temp->link;
}
temp = *head;
while (temp->link != *head) {
temp = temp->link;
}
temp->link = *head;
(*head)->pre = temp;
}
void Display(Node* head) {
if (head == NULL) {
printf("List is empty!\n");
return;
}
Node* temp = head;
do {
printf("%d ", temp->data);
temp = temp->link;
} while (temp != head);
printf("\n");
}
int main() {
Node* head = NULL;
AddNode(&head, 1);
AddNode(&head, 2);
AddNode(&head, 3);
AddNode(&head, 4);
AddNode(&head, 5);
Display(head);
ConvertToDoubleLinkedList(&head);
Display(head);
return 0;
}
```
阅读全文