有序链表插入

时间:2013-12-03 05:32:10

标签: c linked-list

我正在完成一项家庭作业,我会考虑列表的大小,然后是元素。然后我按顺序插入它们。此代码具有使用引用头指针的推送和追加方法。如果我使用已经递增顺序的输入它很好,但推到前面可能是问题是我如何更改headRef?任何帮助表示赞赏。

#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;

}

1 个答案:

答案 0 :(得分:0)

insert_sorted_linked_list()功能更改为:

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

}

并从main调用它:

insert_sorted_linked_list(&head, elements[i]);

由于按值调用,在此函数中调用insertFrontinsertEnd时所做的更改未反映在main中。因此,main()头部保持在3,插入第一个节点。这就是输出错误的原因。