使用链表,输入两个句子,并对其中的单词进行排序
第一个句子可以完美排序,到了第二个句子就运行出错
typedef struct LinkList {
char word[M];
struct LinkList* next;//下一节点
}LNode, * LinkList;
LinkList InitList()
{//初始化链表
LinkList L = (LinkList)malloc(sizeof(LNode));// 为头结点分配空间
if (!L) exit(OVERFLOW);
L->next = NULL;
return L;
}
status InsertList(LinkList L, char* e,int i)
{//在第i个位置之后插入节点
LNode* p = L;
int j = 0;
while (p && j < i)
{
p = p->next;
j++;
}
LinkList s = (LinkList)malloc(sizeof(LNode));
strcpy(s->word, e);
s->next = p->next;
p->next = s;
return OK;
}
void bubble_sort(LinkList L)
{
int i, j;
LNode* p, * q;
char temp[10];
for (p = L->next, i = 1; p; i++, p = p->next)
{
for (q = L->next, j = 1; q; j++, q = q->next)
{
if (strcmp(p->word, q->word) < 0)
{
strcpy(temp,p->word);
strcpy(p->word, q->word);
strcpy(q->word, temp);
}
}
}
}
void showlist(LinkList L)
{
LNode* p = L->next;
while (p)
{
printf("%s ", p->word);
p = p->next;
}
}
void main()
{
LinkList l1 = InitList();
LinkList l2 = InitList();
char word[N][M];
char c = ' ';
int i = 0,j = 0;
printf("请输入第一个句子: ");
while (c != '.' && c != '!' && c != '?')
{
c = getchar();
if (c != ' ' && c != '.' && c != '!' && c != '?')
word[j][i++] = c;
else
{
word[j++][i] = '\0';
i = 0;
}
}
for (i = 0; i < j; i++)
InsertList(l1, word[i], 0);
bubble_sort(l1);
showlist(l1);
i = 0; j = 0; c = ' ';
printf("\n请输入第二个句子: \n");
while (c != '.' && c != '!' && c != '?')
{
c = getchar();
if (c != ' ' && c != '.' && c != '!' && c != '?')
word[j][i++] = c;
else
{
word[j++][i] = '\0';
i = 0;
}
}
for (i = 0; i < j; i++)
InsertList(l2, word[i], 0);
bubble_sort(l2);
showlist(l2);
}
你这个是因为读入数据不对造成的
第一个句子读完后有一个回车需要处理一下,不然下面的读入字符都是错的了
代码修改如下,在下面代码地方加一个 getchar(); 吸收回车符号
bubble_sort(l1);
showlist(l1);
getchar(); /*加上这一句吧回车符号吸收了,在输入字符串和字符的时候要特别注意下*/
i = 0; j = 0; c = ' ';
printf("\n请输入第二个句子: \n");
以下思路由ChatGPT提供
在第二个循环中,您的代码会导致 q 指针始终指向头结点,导致程序出错。为了解决这个问题,您可以在第一个循环中记录下链表的长度,并在第二个循环中使用这个长度来确定循环的次数。例如:
void bubble_sort(LinkList L)
{
int i, j;
LNode* p, * q;
char temp[10];
int length = 0; // 记录链表的长度
for (p = L->next, i = 1; p; i++, p = p->next)
{
length++;
}
for (i = 0; i < length - 1; i++) // 使用 length 来确定循环次数
{
p = L->next;
for (j = 0; j < length - i - 1; j++)
{
q = p->next;
if (strcmp(p->word, q->word) > 0)
{
strcpy(temp,p->word);
strcpy(p->word, q->word);
strcpy(q->word, temp);
}
p = p->next;
}
}
}
在上面的代码中,我们首先遍历链表计算出链表的长度,然后在第二个循环中使用这个长度来确定循环的次数。这样就能保证在排序时遍历到所有的节点。
希望能帮助到您
用这个
#include<stdio.h>
#include <string.h>
//微信公众号:C语言与CPP编程 2020.05.02
int main()
{
int i, j;
char str[10][50], temp[50];
printf("输入10个单词:\n");
for(i=0; i<10; ++i) {
scanf("%s[^\n]",str[i]);
}
for(i=0; i<9; ++i) {
for(j=i+1; j<10 ; ++j)
{
if(strcmp(str[i], str[j])>0)
{
strcpy(temp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], temp);
}
}
}
printf("\n排序后: \n");
for(i=0; i<10; ++i)
{
puts(str[i]);
}
return 0;
}