用c++给链表排序带主函数的
时间: 2023-09-06 20:02:37 浏览: 128
以下是一个使用C语言编写的链表排序的示例代码,包含了主函数:
```c
#include<stdio.h>
#include<stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertNode(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
}
else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
void swapNodes(Node *a, Node *b) {
int temp = a->data;
a->data = b->data;
b->data = temp;
}
void sortList(Node* head) {
Node* current;
Node* index;
if (head == NULL) {
return;
}
else {
for (current = head; current->next != NULL; current = current->next) {
for (index = current->next; index != NULL; index = index->next) {
if (current->data > index->data) {
swapNodes(current, index);
}
}
}
}
}
int main() {
Node* head = NULL;
insertNode(&head, 3);
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 5);
insertNode(&head, 4);
printf("Before sorting: ");
printList(head);
sortList(head);
printf("After sorting: ");
printList(head);
return 0;
}
```
该程序创建了一个链表并初始化了一些节点,然后通过调用`sortList`函数对链表进行排序,最后打印排序前和排序后的链表内容。排序使用冒泡排序算法来实现,通过比较节点的数据并交换位置来完成排序。
阅读全文