补齐以下代码#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; void sort(struct node *head); //采用选择排序法思想,对结点数据进行交换处理 void destroy(struct node* head); struct node* creatlink(); void traverse(struct node* head); int m
时间: 2023-08-07 13:06:43 浏览: 135
代码中缺少函数 `main`,需要补充。
以下是完整代码:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void sort(struct node *head);
void destroy(struct node* head);
struct node* creatlink();
void traverse(struct node* head);
int main() {
struct node *head = creatlink(); // 创建带头结点的链表
sort(head); // 对链表进行排序
traverse(head); // 遍历链表
destroy(head); // 销毁链表
return 0;
}
struct node *creatlink() {
struct node *head = (struct node*)malloc(sizeof(struct node)); // 创建头结点
struct node *p = head;
int num;
printf("请输入数据(输入0结束):\n");
scanf("%d", &num);
while (num) {
struct node *newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = num;
newnode->next = NULL;
p->next = newnode;
p = p->next;
scanf("%d", &num);
}
return head;
}
void sort(struct node *head) {
struct node *p = head->next;
while (p != NULL) {
struct node *q = p->next;
while (q != NULL) {
if (p->data > q->data) {
int temp = p->data;
p->data = q->data;
q->data = temp;
}
q = q->next;
}
p = p->next;
}
}
void traverse(struct node *head) {
struct node *p = head->next;
printf("排序后的链表数据为:\n");
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void destroy(struct node *head) {
struct node *p = head;
while (p != NULL) {
struct node *q = p->next;
free(p);
p = q;
}
}
```
阅读全文