0

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? :/

Impasse
  • 85
  • 9
  • 2
    Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). And note your check of `while(s != EOF)` is incorrect. Try `while(scanf(" %c", &s) == 1) { insert(&startPtr, s); }` with a space added before `%c`. – Weather Vane Jul 03 '19 at 09:26
  • Thank you, leaving a whitespace does it. What's the stop condition for that while cycle? – Impasse Jul 03 '19 at 09:33

0 Answers0