#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct cell {//单链表结点结构体定义
int x;
struct cell* next;
};
struct cell* build(void) {//新建单链表,并将建好的单链表首结点地址返回
struct cell* head, * tmp, * tail;
head = tmp = tail = NULL;
int n;
/*请在以下位置补充完整,实现函数build的功能*/
scanf("%d", &n);
while (n != 0) {
tmp = (struct cell*)malloc(sizeof(struct cell));
if (head == NULL) {
head = tmp;
}
else {
tail->next = tmp;
}
tmp->x = n;
tmp->next = NULL;
tail = tmp;
scanf("%d", &n);
}
return head;//返回单链表头
}
struct cell* sort_1(struct cell* head) {//递增排序链表,head是单链表首结点指针
struct cell* p, * p0, * r, * r0, * q;
p = p0 = r = r0 = q = NULL;
p = head;
if (head == NULL) {
return NULL;
}//空链表
if (head->next == NULL) {
return head;
}//单节点
struct cell* temp;
temp = (struct cell*)malloc(sizeof(struct cell));
temp->x = 0;
temp->next = head;//链接
head = temp;//哨兵节点作为第一个节点
//排序从哨兵后一位开始
p0 = head;
p = p0->next;
r0 = head;
r = r0->next;//初始化
while (p->next) {//for(int i = 0;i<n-1;i++){}
r0 = p;
r = p->next;
while (r) {//for(int j = i+1;j<n;j++){}
if (p->x > r->x) {
r0->next = p;
p0->next = r;//改变跟随的内容;
q = r->next;
r->next = p->next;
p->next = q;//改变后面链接的内容
r = r0->next;
p = p0->next;//复位p,r
}
else {
r0 = r;
r = r->next;
}
}
p0 = p;
p = p->next;
}
struct cell* temp2 = head;
head = head->next;
free(temp2);//释放哨兵节点
return head;
} /* sort */
void print(struct cell* head) {//打印整个单链表,head是单链表首结点指针
/*请在以下位置补充完整,实现函数print的功能*/
while (head) {
printf("%d ", head->x);
head = head->next;
}
}
void release(struct cell* head) {//释放单链表空间,head是单链表首结点指针
/*请在以下位置补充完整,实现函数release的功能*/
struct cell* temp;
while (head) {
temp = head;
head = head->next;
free(temp);
}
}
int main(void) {
struct cell* head;
head = build();
if (head != NULL) {
head = sort(head);
print(head);
}
else
printf("NULL");
release(head);
return 0;
}
03-14
4538
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-01
3545
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-21
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交