实现不带头结点的双向循环链表的创建,实现该双向循环链表上数据的排序数据结构代码
时间: 2023-04-06 14:04:08 浏览: 193
以下是实现不带头结点的双向循环链表的创建以及排序的数据结构代码:
```c++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* prev;
Node* next;
};
Node* createList(int arr[], int n) {
Node* head = NULL;
Node* tail = NULL;
for (int i = 0; i < n; i++) {
Node* newNode = new Node;
newNode->data = arr[i];
newNode->prev = tail;
newNode->next = NULL;
if (tail == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
if (head != NULL) {
head->prev = tail;
tail->next = head;
}
return head;
}
void printList(Node* head) {
Node* cur = head;
while (cur != NULL) {
cout << cur->data << " ";
cur = cur->next;
if (cur == head) {
break;
}
}
cout << endl;
}
void sortList(Node* head) {
if (head == NULL) {
return;
}
Node* cur = head;
while (cur->next != head) {
Node* minNode = cur;
Node* p = cur->next;
while (p != head) {
if (p->data < minNode->data) {
minNode = p;
}
p = p->next;
}
if (minNode != cur) {
int temp = cur->data;
cur->data = minNode->data;
minNode->data = temp;
}
cur = cur->next;
}
}
int main() {
int arr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
int n = sizeof(arr) / sizeof(arr[0]);
Node* head = createList(arr, n);
cout << "Original list: ";
printList(head);
sortList(head);
cout << "Sorted list: ";
printList(head);
return 0;
}
```
该代码实现了不带头结点的双向循环链表的创建和排序功能。在创建链表时,每个节点的前驱指针指向前一个节点,后继指针指向后一个节点,最后一个节点的后继指针指向头节点,头节点的前驱指针指向最后一个节点。在排序时,使用选择排序算法,每次找到未排序部分中的最小值,与当前节点交换。
阅读全文