设计一个算法,建立按元素值(设线性表元素为非负整数)递增的有序单链表。(数据输入次序任意)
2条回答 默认 最新
- 技术专家团-小桥流水 2022-03-23 22:05关注
有两种方式,一是输入数据后先建立链表,然后排序;二是在插入的时候直接排序。
方法一(建立链表后再排序):代码如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct link_node { int data; struct link_node* next; }node,*linklist; linklist createList() { linklist L; linklist n,p; char ch; L = (linklist)malloc(sizeof(node)); if (L == NULL) { printf("error"); return 0; } p = L; printf("请输入数字,并以回车结束:\n"); while(1) { n = (linklist)malloc(sizeof(node)); scanf("%d",&n->data); n->next = NULL; p->next = n; p = n; if( (ch=getchar()) == '\n') break; } return L; } void print(linklist head) { linklist p; p = head->next; while(p) { printf("%d ",p->data); p = p->next; } printf("\n"); } //排序 void BubbleSort(linklist List) { node * p, * q, * tail; tail = NULL; while((List->next->next) != tail) { p = List; q = List->next; while(q->next != tail) { if( q->data > q->next->data ) { p->next = q->next; q->next = q->next->next; p->next->next = q; q = p->next; } q = q->next; p = p->next; } tail = q; } } //释放内存 void release(linklist head) { linklist p; while(head) { p = head->next; free(head); head = p; } } int main() { linklist head = createList(); printf("链表信息:"); print(head); BubbleSort(head); printf("排序后:"); print(head); release(head); return 0; }
方法二(输入时直接排序):
代码:#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct link_node { int data; struct link_node* next; }node,*linklist; linklist createList() { linklist L; linklist n,p,front; char ch; L = (linklist)malloc(sizeof(node)); L->next = NULL; if (L == NULL) { printf("error"); return 0; } printf("请输入数字,并以回车结束:\n"); while(1) { n = (linklist)malloc(sizeof(node)); scanf("%d",&n->data); n->next = NULL; front = L; p = front->next; while(p) { if(p->data > n->data) { front->next = n; n->next = p; break; }else { front = p; p = p->next; } } if(p==NULL) { front->next = n; } if( (ch=getchar()) == '\n') break; } return L; } void print(linklist head) { linklist p; p = head->next; while(p) { printf("%d ",p->data); p = p->next; } printf("\n"); } //释放内存 void release(linklist head) { linklist p; while(head) { p = head->next; free(head); head = p; } } int main() { linklist head = createList(); printf("链表信息:"); print(head); release(head); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 3无用
悬赏问题
- ¥15 速帮,学校需要在外上班没空
- ¥15 人在外地出差,速帮一点点
- ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
- ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
- ¥50 vue router 动态路由问题
- ¥15 关于#.net#的问题:End Function
- ¥15 无法import pycausal
- ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
- ¥15 weditor无法连接模拟器Local server not started, start with?
- ¥20 6-3 String类定义