设待排序的记录序列用单链表作存储结构,编写直接插入排序或简单选择排序的程序使用c++语言编写
时间: 2024-05-15 19:18:09 浏览: 18
可以,以下是单链表直接插入排序的程序示例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkedList;
LinkedList createLinkedList() {
LinkedList L = (LinkedList)malloc(sizeof(Node));
L->next = NULL;
return L;
}
void insert(LinkedList L, int data) {
Node *p = L;
while (p->next && p->next->data < data) {
p = p->next;
}
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = p->next;
p->next = newNode;
}
void insertionSort(LinkedList L) {
if (L->next == NULL || L->next->next == NULL) {
return;
}
Node *p = L->next->next;
L->next->next = NULL;
while (p != NULL) {
Node *q = p;
p = p->next;
q->next = NULL;
insert(L, q->data);
}
}
void printLinkedList(LinkedList L) {
Node *p = L->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
}
int main() {
int n, data;
scanf("%d", &n);
LinkedList L = createLinkedList();
for (int i = 0; i < n; ++i) {
scanf("%d", &data);
insert(L, data);
}
insertionSort(L);
printLinkedList(L);
return 0;
}
```
其中,createLinkedList 函数用于创建一个空的单链表,insert 函数用于将指定的数据插入到单链表中,并保证单链表中的数据有序,insertionSort 函数用于对单链表进行直接插入排序,printLinkedList 函数用于输出单链表中的全部数据。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)