I am trying to write the program for sorted-liked list. By the way if I try to send the data to fuction from user input, the program gets crashed, but if I call the function with given data, it works fine. Could you tell me what's the problem. I comment out the problem part below (Case one and Case two).
Thank you.
Your addSong() function is wrong (the main else case). Also, are you trying to create a singly linked list or a doubly linked list? Your songListStr struct contains two pointers like you want it to be doubly linked, but the "prev" (review) pointer is always set to NULL.
At a glance, I could tell you that your addSong() would need a simple loop to check where the new one needs to be inserted in the existing list.
First time, when it creates a new node it keeps the newone as head, but next time onwords, it is checking with only the songHead which would check only at second position and would not place the newly inserted at right place.
The while loops look errouneous though.
You are initializing tempHead with songHead but you are not using either.
Have a new loop to check with the existing nodes one after another starting from first and find right place for insertion. Within the loop you keep moving ahead until last but one but not so NULL.
The revised code would look like:
void songList::addSong(char * songName)
{
songListStr * newSong = NULL; // pointer to hold node
songListStr * tempHead = NULL;
songListStr * preHead = NULL;
songListStr * nextHead = NULL;
//create new one hear
newSong = new songListStr;
newSong->song = songName;
newSong->next = newSong->prev = NULL;
if (songHead == NULL)
{
songHead = newSong;
return; // you are done here
}
elseif (strcmp(songName,songHead->song) < 0) // needs to be inserted before head
{
newSong->next = songHead;
songHead = newSong; // the newone is the head
}
else //needs to find a right place for insertion
{
tempHead = songHead; // start from head (first)
while (strcmp(songName,temHead->song) < 0 && tempHead->next) //check upto last node
{
tempHead = temp->next;
}
if ( strcmp(songName,temHead->song) < 0 ) // insert just before the current position
{
newSong->prev = tempHead->prev;
tempHead->prev = newSong;
newSong->next = tempHead;
return;
}
else // insert just after the current position
{
newSong->next = tempHead->next;
tempHead->next = newSong;
newSong->prev = tempHead;
return;
}
}
}