插入节点并按字母顺序排列它们

时间:2015-11-20 22:12:29

标签: c string pointers linked-list singly-linked-list

我有一个歌曲库,用户将在其中输入歌曲并将成为链接列表,但是我在有序列表中的插入不起作用。

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。

1 个答案:

答案 0 :(得分:2)

问题是你在比较指针而不是比较指针指向的字符串。

例如,在本声明中,我认为应该有

if (head == NULL || songName < head -> songName) {

而不是

strcmp

同样适用于比较指针而不是字符串本身的其他语句。

那就是你应该使用标题<string.h>中声明的标准C函数while (current -> link != NULL && songName <= current -> link -> songName) current = current -> link; 来比较字符串而不是指针。

也在这个循环中

songName <= current -> link -> songName

条件current -> link -> songName是错误的。当songName小于或等于while (current -> link != NULL && strcmp( songName, current -> link -> songName ) >= 0 ) current = current -> link; 时,循环必须迭代。

因此它应该看起来像

import os

#Lists files in the Import folder
for file in os.listdir("Imports"):
    if file.endswith(".wav" or ".mp3"or ".txt"):
        print file

#imports file into the editor
selected_file = raw_input("Which do you wish to modify?")

if selected_file in ("Imports"):
    new_file = selected_file
    print new_file
else:
    print("File does not exist or not available. please select another.")


It outputs:
boom.wav
Which do you wish to modify?
相关问题