实现不带头结点的双向循环链表的创建,然后实现该双向循环链表上数据的排序完整代码
时间: 2023-04-08 17:00:25 浏览: 126
以下是实现不带头结点的双向循环链表的创建,并实现该双向循环链表上数据的排序的完整代码:
```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;
tail->next = newNode;
newNode->prev = tail;
newNode->next = head;
head->prev = 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;
}
if (prev != cur->prev) {
Node* next = cur->next;
prev->next = cur;
cur->prev->next = next;
cur->next = prev->next;
next->prev = cur;
cur->prev = prev;
prev->next = cur;
cur = next;
} else {
cur = 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;
}
```
输出结果为:
```
Original list: 3 1 4 2 5
Sorted list: 1 2 3 4 5
```
阅读全文