实现不带头结点的双向循环链表的创建,并进行数据的排序的代码
时间: 2023-04-07 20:00:30 浏览: 101
以下是实现不带头结点的双向循环链表的创建,并进行数据的排序的代码:
```c++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* prev;
Node* next;
};
Node* createNode(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
void insertNode(Node*& head, Node* newNode) {
if (head == NULL) {
head = newNode;
head->prev = head;
head->next = head;
}
else {
Node* tail = head->prev;
newNode->next = head;
newNode->prev = tail;
head->prev = newNode;
tail->next = newNode;
}
}
void sortList(Node*& head) {
if (head == NULL || head->next == head) {
return;
}
Node* cur = head->next;
while (cur != head) {
Node* prev = cur->prev;
while (prev != head && prev->data > cur->data) {
prev = prev->prev;
}
Node* next = cur->next;
if (prev != cur->prev) {
prev = prev->next;
prev->prev->next = next;
next->prev = prev->prev;
prev->prev = cur->prev;
cur->prev->next = prev;
cur->next->prev = prev;
prev->next = cur->next;
}
cur = next;
}
}
void printList(Node* head) {
if (head == NULL) {
return;
}
Node* cur = head;
do {
cout << cur->data << " ";
cur = cur->next;
} while (cur != head);
cout << endl;
}
int main() {
Node* head = NULL;
insertNode(head, createNode(3));
insertNode(head, createNode(1));
insertNode(head, createNode(4));
insertNode(head, createNode(2));
insertNode(head, createNode(5));
cout << "Original list: ";
printList(head);
sortList(head);
cout << "Sorted list: ";
printList(head);
return 0;
}
```
这段代码实现了不带头结点的双向循环链表的创建,并进行数据的排序。其中,createNode() 函数用于创建新节点,insertNode() 函数用于插入新节点,sortList() 函数用于排序链表,printList() 函数用于打印链表。
阅读全文