I can't understand why this happens. I've had this happen already a few times before, and I've never come to a solution. When first inputting "a" I get the following:
a
The list is: a --> NULL The list is:
--> a --> NULL
When inputting one more character I get:
b
The list is:
--> a --> b --> NULL The list is:
--> --> a --> b --> NULL
This is the source code:
#include <stdio.h>
#include <stdlib.h>
struct listNode{
char data;
struct listNode *nextPtr;
};
typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;
void insert(ListNodePtr *Node, char value);
void printList(ListNodePtr Node);
void main(){
ListNodePtr startPtr = NULL;
char s;
while(s != EOF){
scanf("%c", &s);
insert(&startPtr, s);
}
}
void insert(ListNodePtr *Node, char value){
ListNodePtr newPtr = malloc(sizeof(ListNode));
if(newPtr != NULL){
newPtr->data = value;
newPtr->nextPtr = NULL;
ListNodePtr previousPtr = NULL;
ListNodePtr currentPtr = *Node;
while(currentPtr != NULL && value > currentPtr->data){
previousPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
}
if(previousPtr == NULL){
newPtr->nextPtr = *Node;
*Node = newPtr;
}
else{
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
printList(*Node);
}
else{
printf("%c not inserted: no memory available.");
}
}
void printList(ListNodePtr currentPtr){
puts("The list is: ");
while(currentPtr != NULL){
printf("%c --> ", currentPtr->data);
currentPtr = currentPtr->nextPtr;
}
puts("NULL");
}
Any ideas? :/