我有一个歌曲库,用户将在其中输入歌曲并将成为一个链接列表,但是我插入到有序列表中的操作不起作用。
Node *insertIntoOrderedList(Node *head, char *songName, char *artist, char *genre) {
if (head == NULL || songName < head -> songName) {
return newNode(songName, artist, genre, head); // a new head of the list
}
Node *current = head;
while (current -> link != NULL && songName <= current -> link -> songName)
current = current -> link;
current -> link = newNode(songName, artist, genre, current -> link);
return head;
}
现在打印链表时,会按照我输入的顺序排列,所以如果我输入B、A、C,打印链表时会是BAC,而不是ABC。
最佳答案
问题在于您正在比较指针而不是比较指针指向的字符串。
例如在这个声明中我认为应该有
if (head == NULL || strcmp( songName, head -> songName ) < 0 ) {
而不是
if (head == NULL || songName < head -> songName) {
这对于比较指针而不是字符串本身的其他语句也是有效的。
那就是你应该使用标准C函数strcmp
在 header <string.h>
中声明比较字符串而不是指针。
也在这个循环中
while (current -> link != NULL && songName <= current -> link -> songName)
current = current -> link;
条件songName <= current -> link -> songName
是错的。循环必须迭代 while current -> link -> songName
小于或等于songName
.
因此它应该看起来像
while (current -> link != NULL && strcmp( songName, current -> link -> songName ) >= 0 )
current = current -> link;
关于c - 插入节点并按字母顺序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33836918/