I'm working with linkedlist. I want to create a loop that allows the user to add nodes to the list. My output always has two extra blank nodes. I believe it has something to do with the way I am using the input functions to both take input and cancel the loop but I can't pin point where the problem is.
I've tried a variety of variations including terminating as loop expression and with while(1) terminating inside the loop.
I hope it doesn't matter that I'm using Ubuntu on Windows 10 but who knows.
#include <stdio.h>
#include <stdlib.h>
#include <stdio_ext.h>
#include <stdbool.h>
typedef struct node {
int val;
struct node * next;
} node_t;
node_t * init_node();
void print_list(node_t * head);
int main(){
node_t * new = init_node();
node_t * head = new;
int c;
printf("\n\tAt any time Press 'N' to quit.\n");
do{
if(c == 'n' || c =='N') {
break;
}
//__fpurge(stdin);
printf("\n\tEnter a value for the new node: ");
scanf("\n%d", &new -> val);
new -> next = init_node();
new = new -> next;
} while(c = getc(stdin) != 'N' && c != 'n');
printf("\n\t");
print_list(head);
return 0;
}
node_t * init_node(){
node_t * temp = (node_t *) malloc( sizeof(node_t *) );
temp -> next = NULL;
return temp;
}
void print_list(node_t * head){
node_t * current = head;
printf("\n\t");
while(current != NULL){
printf("%d->",current -> val);
current = current -> next;
}
printf("null\n");
}
With inputs: 1, 2, 3 ...
The desired output is:
>
1->2->3->null
The current output is:
>
1->2->3->0->0->null
Thanks in advance!