【问题标题】:I try to write code for linked lists in C我尝试在 C 中为链表编写代码
【发布时间】:2020-06-17 20:55:28
【问题描述】:

我必须为实验室编写代码,但我不明白如何使用哪个函数插入节点。

结构列表 {int值; 结构列表 * 下一个;};

int main()........ 代码说我们询问用户他想在列表中插入多少个整数(N).. so easy printf, scanf 然后..它会询问数字并按照给出的顺序列出它们。 我认为我需要一个 for 循环 但我知道许多插入功能,例如 insertAfter、push 等 我需要你帮忙!谢谢你

【问题讨论】:

  • 首先,你定义的结构不是列表。它只是列表的 1 个节点的组件。因此,也许称其为“列表”具有误导性。其次,由于您将指针定义为第二个成员,我知道您已经研究过如何动态分配元素。您需要:当询问数字时,您将逐个节点构建您的列表,并分配它们。然后,您将遍历整个元素链(您创建的节点列表)并显示数字。
  • 感谢您的帮助!是的,这不是一个列表:)。
  • 事实上,你并没有“插入”节点。您告诉一个节点哪个是链中的下一个节点(通过next 数据成员)。但是我看到有人已经给了你一个完整的答案,没有解释......(*叹息*)

标签: c list function insert nodes


【解决方案1】:

你给出的结构代表一个节点。您首先创建列表的head,然后您需要逐个读取数字,为每个数字创建一个节点并使用代码中定义的append() 函数将其附加到列表的末尾下面给出。

这是您需要的完整程序(功能代码取自 geeksforgeeks.org):

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

// A linked list node 
struct Node 
{ 
  int data; 
  struct Node *next; 
}; 

/* Given a reference (pointer to pointer) to the head 
   of a list and an int, appends a new node at the end  */
void append(struct Node** head_ref, int new_data) 
{ 
    /* 1. allocate node */
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 

    struct Node *last = *head_ref;  /* used in step 5*/

    /* 2. put in the data  */
    new_node->data  = new_data; 

    /* 3. This new node is going to be the last node, so make next of 
          it as NULL*/
    new_node->next = NULL; 

    /* 4. If the Linked List is empty, then make the new node as head */
    if (*head_ref == NULL) 
    { 
       *head_ref = new_node; 
       return; 
    } 

    /* 5. Else traverse till the last node */
    while (last->next != NULL) 
        last = last->next; 

    /* 6. Change the next of last node */
    last->next = new_node; 
    return; 
} 


// This function prints contents of linked list starting from head 
void printList(struct Node *node) 
{ 
  while (node != NULL) 
  { 
     printf(" %d ", node->data); 
     node = node->next; 
  } 
} 


int main() 
{ 
  /* Start with the empty list */
  struct Node* head = NULL; 

  int n;
  scanf("%d", &n);

  for(int i=0; i<n; i++) {
    int e;
    scanf("%d", &e);
    append(&head, e);
  }

  printList(head);
}

【讨论】:

  • 你的帮助对我来说太重要了!!祝你有美好的一天!
  • 我怎样才能投票给你答案?我是第一次来,很多事情都不知道!!
  • 答案的左上角显示“-1”(它表示对该答案的投票数)。在其上方和下方有向上和向下箭头。您只需点击“向上”箭头即可为答案投票。
猜你喜欢
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多