Hi guys!
I am writing this simple program, to learn how to insert into linked list. It seems to be working but for some reason, there is a one already in the list, when I have not even added any nodes.
For example if I add nodes 1,2,3,4
If will print 4->3->2->11
Where is the extra one coming from?
Thanks!
Code:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node* insertNode(struct node* list, int value);
void printList(struct node* list);
int main (void) {
int number = 0;
int selection = 0;
struct node* mainList;
mainList = NULL;
while(number != -1) {
scanf("%d", &number);
if(number != -1)
mainList = insertNode(mainList, number);
}
while (selection != 10) {
printf("1. Print the linked list.\n\n");
printf("10. Quit\n\n");
scanf("%d", &selection);
if(selection == 1) {
printList(mainList);
}
}
system("PAUSE");
return 0;
}
struct node* insertNode(struct node* list, int value) {
struct node* newNode;
newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = value;
newNode->next = NULL;
if(list == NULL) {
list = newNode;
}
else {
newNode->next = list;
list = newNode;
}
return list;
}
void printList(struct node* list) {
while(list != NULL) {
printf("->%d", list->data);
list = list->next;
}
}