简体   繁体   中英

ordered linked list insertion

I am working on a homework assignment where I take in the size of a list and then the elements. I then insert them in increasing order. This code has a push and append method using referencing to the head pointer. If I use an input that is already in increasing order its fine, but pushing onto the front might be the problem is it how I am changing the headRef? Any help appreciated.

#include <stdio.h>
#include <stdlib.h>

typedef struct node item;
  struct node{
  int data;
  struct node* next;

};

void insertFront(item** headRef, int new_data)
{

  item* new_node = (item*) malloc(sizeof(item));

  new_node->data  = new_data;

  new_node->next = (*headRef);

  (*headRef)    = new_node;
}

//using reference to pointer adds to end
void insertEnd(item** headRef, int new_data)
{

  item* new_node = (item*) malloc(sizeof(item));

  //pointer head for iterating through list
  item* last = *headRef;  

  new_node->data  = new_data;

  new_node->next = NULL;

  if (*headRef == NULL)
  {
     *headRef = new_node;
     return;
  }

  while (last->next != NULL)
    last = last->next;

  last->next = new_node;
  return;
}

//utility function to insert data sorted
void insert_sorted_linked_list(item* head, int val){
 if(val > head->data){
   insertEnd(&head, val);
 }
 else{
  insertFront(&head, val);
 }

}

void printList(item *node)
{
  while (node != NULL)
  {
    printf("%d  ", node->data);
    node = node->next;
  }
  printf("\n");
}

int main(){

  printf("Enter in size of the list followed by as many elements: ");
  int size;
  scanf("%d", &size);
  int elements[size];
  int i = 0;
  for(i=0; i<size; i++){
  scanf("%d", &elements[i]);
}
item *head = NULL;
//makes sure the list is not null
insertEnd(&head, elements[0]);
//iterates to populate list
for(i = 1; i < size; i++){
  insert_sorted_linked_list(head, elements[i]);
}
printList(head);
return 0;

}

Change your insert_sorted_linked_list() function to :

void insert_sorted_linked_list(item** head, int val){
 if(val > (*head)->data){
   insertEnd(head, val);
 }
 else{
  insertFront(head, val);
 }

}

and call it from main as :

insert_sorted_linked_list(&head, elements[i]);

The changes made to head in calls to insertFront and insertEnd from this function is not getting reflected in main because of the call by value. Hence in main() head remains at 3, the first node inserted. Thats why the output is wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM