【问题标题】:Adding a node to the head of the linked list将节点添加到链表的头部
【发布时间】:2018-09-19 12:03:16
【问题描述】:

我想在基于数字的排序链表中添加一个节点。这是结构:

struct node {
  int number;
  struct node *next;
}

我能够正确添加到排序链表,但不能让它改变头部。

很遗憾,我无法更改函数声明的格式,所以这是我的函数:

int create(struct node *head, int number) {
   struct node *newNode = malloc(sizeof(struct node));
   newNode->number = number;
   struct node *current = head;

   if (current->number == -1) {
     newNode->next = NULL;
     *head= *newNode;
     return 1;
   }

   //Checking if head's number is bigger than init
   if (current->number > number) {
     newNode->next = current;
     *head = *newNode;
   } else {
     while(current->next != NULL && (current->number <= number)) {
      current = current->next;
     }
    newNode->next = current->next;
    current->next = newNode;
   }
   return 1;
}

对函数的调用是(注意我也无法更改):

struct node *list;
list = initializeList();
int num;
num = create(list, 5);
num = create(list, 1);

第二次调用后,列表应该是 1->5。但它变成了 1->1->1->1->.....

编辑:初始化列表的代码:

struct node * initializeList() {
  struct node *head;
  head = malloc(sizeof(struct node));
  head->next = NULL;
  head->number = -1;
  return head;
}

【问题讨论】:

  • 您是否也可以发布initializeList() 的代码,似乎相关
  • 我不明白你为什么需要这条线*head = *newNode;
  • @kiranBiradar *head = *newNode 行在那里,所以我可以将头部分配给新节点。
  • @rtpax 添加了initializeList() 代码
  • 我的行为与您描述的不同。我得到的结果列表是 0->5->1。请注意,0 来自initializeList 中的未初始化值,因此可能会有所不同。

标签: c singly-linked-list


【解决方案1】:

我对@9​​87654321@ 函数进行了一些编辑以解决问题。

首先,如果列表的头部有number == -1,则不应分配新的node,因为您只是替换数字。

其次,如果需要插入一个节点,前一个节点需要知道下一个节点去哪里,所以不能只用新节点替换前一个节点。您需要将前一个节点指向新节点并将新节点指向移位节点;或者你可以将当前节点复制到新节点中,并将新节点的编号放入当前,并将其指向新节点。第二种在这里效果更好,因为它不需要改变头部(如果需要在前面,我们就不能这样做)。

int create(struct node *head, int number) {
  struct node *current = head;

  if (current->number == -1) {
    current->number = number;//just replace the number, no need for anything else
    return 1;
  }

  //allocate only if we must insert
  struct node *newNode = malloc(sizeof(struct node));

  //no longer need to check if head
  while(current->next != NULL && (current->number <= number)) {
    current = current->next;
  }
  if(current->next == NULL && current->number < number) {//check if number needs to go at the end
    current->next = newNode;
    newNode->next = NULL;
    newNode->number = number;
  } else {
    *newNode = *current;//newNode will go after current, but with current's values
    current->number = number;//replace current with the number to "insert" it
    current->next = newNode;//point to the next node
  }
  return 1;
}

【讨论】:

    【解决方案2】:

    为节点分配一个索引值,并将其他元素移动一个。我的意思是您可以将一个添加到另一个元素的每个值并在循环中进行迭代。

    【讨论】:

    • 他不应该需要添加索引来使链表工作
    猜你喜欢
    • 2012-09-22
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    相关资源
    最近更新 更多