I am trying to create a linked list that will take the input from the user, order it, and print it out once the user inputs 0 or a negative number. Somewhere my code is adding a “0” to the begining of the print loop.
Example: I input 1-2-3-4-5. The program then returns 0-1-2-3-4-5.
Example2: I input 1-2-3-4-5. The program then returns 0-5-1-2-3-4. Which is also a problem for me because i eventually need to make the program order the inputed values from least to greatest. But for right now im focused on getting it to take the input 1-2-3-4-5 and print 1-2-3-4-5.
#include <stdio.h>
#include <stdlib.h>
struct listNode{
int data;
struct listNode *next;
};
//prototypes
void insertNode(struct listNode *Head, int x);
void printList(struct listNode *Head);
int freeList(struct listNode *Head, int x);
//main
int main(){
struct listNode Head = {0, NULL};
int x = 1;
printf("This program will create an odered linked list of numbers greater"
" than 0 until the user inputs 0 or a negative number.\n");
while (x > 0){
printf("Please input a value to store into the list.\n");
scanf("%d", &x);
if (x > 0){
insertNode(&Head, x);
}
}
printList(&Head);
system("PAUSE");
}
void insertNode(struct listNode * Head, int x){
struct listNode *newNode, *current;
newNode = malloc(sizeof(struct listNode));
newNode->data = x;
newNode->next = NULL;
current = Head;
while (current->next != NULL && current->data < x)
{
current = current->next;
}
if(current->next == NULL){
current->next = newNode;
}
else{
newNode->next = current->next;
current->next = newNode;
}
}
void printList(struct listNode * Head){
struct listNode *current = Head;
while (current != NULL){
if(current > 0){
printf("%d \n", *current);
}
current = current->next;
}
}
It has a zero in the list because you put it there:
If you want a quick fix, change the line in
printList()and anything else that processes the list from:to:
This will start at the second element of the list, ignoring the one you put there to start with.
However, a better way is probably not to have that extraneous element at all:
There’s a couple of other things I’ve cleaned up there as well, such as changing
*currentto the more explicitcurrent->data, passing a pointer to the head so you can change it, and making a slight modification to the main input loop. Here’s a sample run: