This program is meant to insert an element in the middle of a linked list, but I left out functions that aren't in question.
At first I wrote it with assigning HEAD and CURRENT elements to NULL globally and it worked fine. With locally assigned variables in main() it doesn't work. Specifically, the while loop in main is infinite because of the faulty insertDataToEnd function. How could I fix it? Also, before I wrote insertDataToEnd differently and it printed only first and last elements of the list, could the problem be with printList ?
EDIT (again): still having some issues processing all the new information on structures. Now I have this sortList function to swap elements so they would be in inclining order. I get an error only when the function is used.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}node_t;
void insertDataToEnd(int value, struct node **head){
struct node *link = (struct node*) malloc(sizeof(node_t));
link -> data = value;
link -> next = NULL;
node_t *current = *head;
if(*head == NULL){
*head = link;
}
else{
while(current -> next != NULL){
current = current -> next;
}
current -> next = link;
}
}
void printList(struct node* head){
node_t *current = head;
while(current != NULL){
printf("%d -> ", current -> data);
current = current -> next;
}
printf("NULL\n");
}
void sortList(int count, struct node* head){
int i, j, temp;
count += 1;
struct node *current;
struct node *next;
for(i = 0; i < count; i++){
current = head;
next = current -> next;
for(j = 1; j < count + 1; j++){
if(current -> data > next -> data){
temp = current -> data;
current -> data = next -> data;
next -> data = temp;
}
current = current->next;
next = next->next;
}
}
}
void insertElement(int value, int k, struct node** head){
node_t *elemk = (struct node*) malloc (sizeof(node_t));
node_t *elem = (struct node*) malloc (sizeof(node_t));
elemk = *head;
int i = 2;
while (i < k && elemk != NULL){
elemk = elemk -> next;
i++;
}
if(i == k){
printf("element inserted.\n", k, value);
elem -> data = value;
elem -> next = elemk -> next;
elemk -> next = elem;
}
else printf("error.\n");
}
int main()
{
struct node *head = NULL;
int value, readValue, k;
int i = 0;
printf("enter data.\n");
while(1){
scanf("%d", &value);
insertDataToEnd(value, &head);
i++;
if (i == 4) break;
}
sortList(i, head);
printf("insert element\n");
scanf("%d %d", &readValue, &k);
insertElement(readValue, k, &head);
printList(head);
return 0;
}
calling insertDataToEnd(value, current);doesn't modifycurrent? BTW what issortList?**ininsertDataToEnd, similar to what has been done ininsertFirstElement. TheprintListfunction looks OK.insertFirstElementand ainsertDataToEndfunction. You can write one single function that handles the case whereheadis NULL. This would also simplify themainfunction.insertDataToEndhas to undergo some changements. If you understand howinsertFirstElement(which is correct) works, you should be able to find out how to modifyinsertDataToEnd.