首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有序链表插入

有序链表插入
EN

Stack Overflow用户
提问于 2013-12-03 05:32:10
回答 1查看 857关注 0票数 0

我正在做一项家庭作业,在作业中我考虑到了一个列表的大小,然后是元素。然后我将它们按递增顺序插入。此代码具有使用引用头指针的推送和追加方法。如果我使用的输入已经在增加的顺序,它可以,但推到前面可能是问题,这是我如何改变headRef?任何帮助都很感激。

代码语言:javascript
复制
#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;

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-03 05:54:51

insert_sorted_linked_list()函数更改为:

代码语言:javascript
复制
void insert_sorted_linked_list(item** head, int val){
 if(val > (*head)->data){
   insertEnd(head, val);
 }
 else{
  insertFront(head, val);
 }

}

并从main调用它为:

代码语言:javascript
复制
insert_sorted_linked_list(&head, elements[i]);

这个函数调用insertFrontinsertEnd时所做的更改没有在main中得到反映,因为调用是通过值进行的。因此,在main()头保持在3,第一个节点插入。这就是为什么输出是错误的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20343614

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档