|
发表于 2020-5-21 16:22:17
|
显示全部楼层
本帖最后由 sunrise085 于 2020-5-21 17:16 编辑
你这个程序之所以没有对第一个进行排序,是因为在第34行,条件判断中,直接判断的的第二个和第三个的大小,根本没有考虑第一个节点
另外,排序的外层循环次数为什么是k啊
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct Str
- {
- char a[10];
- struct Str *next;
- };
- int main()
- {
- struct Str *p,*q,*t,*head,*tail;
- p = head = tail = NULL;
- int n,k,i;
- char b[10];
- scanf("%d %d",&n, &k);
- for(i=0; i<n; i++)
- {
- p = (struct Str *)malloc(sizeof(struct Str));
- scanf("%s", b);
- strcpy(p->a, b);
- if(head == NULL)
- head = p;
- else
- tail->next = p;
- tail = p;
- }
- tail->next = NULL; //以上为输入到链表中,首地址为head
- for(int i=0;i<n-1;i++)
- {
- p=q=head;
- while(p->next!=NULL){
- if(strcmp(p->a, p->next->a)>0){
- //节点的交换
- if(p==head)
- head=p->next;
- else
- q->next=p->next;
- q=q->next;
- p->next=q->next;
- q->next=p;
- //执行完上面的过程后,为了能够让p顺利地执行移动到交换后的下一位 .
- p=q;
- }
- q=p; //为了能让q保持在p的前面
- p=p->next; //p指针后移,即p变成了在q的前面
- }
- }
- for(i=0; i<n; i++)
- {
- printf("%s\n", head->a);
- head = head->next;
- }
- }
复制代码 |
|