У меня есть один связанный список, в который я могу вставить до 4 значений символов. Моя цель - заставить работать вставку, которая у меня есть, но проблема в том, что если заголовок связанного списка имеет большее значение, чем другие, он будет заполнен только заголовком
У меня есть структура
struct listNode {
char data; /
struct listNode *nextPtr;
};
У меня есть функция вставки
void insert(ListNode *sPtr, char value)
{
ListNode *newPtr;
ListNode *previousPtr;
ListNode *currentPtr;
newPtr = malloc(sizeof(ListNode)); // create node
if (newPtr != NULL) {
newPtr->data = value;
newPtr->nextPtr = NULL;
previousPtr = NULL;
currentPtr = sPtr;
while (currentPtr != NULL && value >= currentPtr->data) {
previousPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
} // end while
// insert new node at beginning of list
if (previousPtr == NULL) {
newPtr->nextPtr = sPtr;
sPtr = newPtr;
} // end if
else { // insert new node between previousPtr and currentPtr
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
} // end else
} // end if
else {
printf("%c not inserted. No memory available.\n", value);
} // end else
} // end function insert
В моем списке печати
void printList(ListNode *currentPtr)
{
puts("The list is:");
// while not the end of the list
while (currentPtr != NULL) {
printf("%c --> ", currentPtr->data);
currentPtr = currentPtr->nextPtr;
} // end while
puts("NULL\n");
} // end function printList
В моем основном
int main(void)
{
ListNode *startPtr = NULL;
ListNode *newPtr = NULL;
ListNode *headPtr = NULL;
unsigned int choice = 4;
char item;
printf("%s", "Enter a character: ");
scanf("\n%c", &item);
newPtr = malloc(sizeof(ListNode)); // create node
headPtr = newPtr;
if (newPtr != NULL) { // is space available
newPtr->data = item;
newPtr->nextPtr = NULL;
startPtr = newPtr;
}
printList(headPtr);
printf("%s", "Enter a character: ");
scanf("\n%c", &item);
insert(headPtr, item);
printList(headPtr);
printf("%s", "Enter a character: ");
scanf("\n%c", &item);
insert(headPtr, item);
printList(headPtr);
printf("%s", "Enter a character: ");
scanf("\n%c", &item);
insert(headPtr, item);
printList(headPtr);
}
Итак, если бы я запустил код и ввел в KQLR, вы бы увидели
Input order: K Q L R
Output order: K L Q R
Но если бы я ввел R Q L K
, я бы получил
Input order: R Q L K
Output order: R
Почему это происходит и как Я чиню это?