【问题标题】:Add an element at the end of a linked list在链表末尾添加一个元素
【发布时间】:2020-09-11 02:22:22
【问题描述】:

我想用链表做一个队列,但我做不到! 我能知道问题出在哪里吗?因为它让我只插入两个值!

typedef struct list
{
    int data;
    struct list* next;
}list;
void move_forward(list* head,list* node)
{
    if(head==NULL)  exit(1);
    while(head->next!=NULL)
       head=head->next;
    head->next=node;
}
list* insert(list* head,int value)
{
    list* node=(list*)malloc(sizeof(list));
    node->data=value;
    node->next=NULL ;
    if(head==NULL)
        head=node;
    move_forward(head,node);
    return head;
}

【问题讨论】:

  • 你能提供一个minimal verifiable example吗?包括您的测试代码,并提供准确的预期结果和实际结果。对于初学者,在insert 中,您可能需要在head==NULL 情况下使用return,而不是继续调用move_forward
  • 是的!有效!!我可以知道为什么我的代码不起作用吗??
  • 好吧,move_forward 应该做什么?它将node 添加到head 列表的末尾。但是在head==NULL 的情况下headnode 是相同的。所以在这种情况下调用move_forward 就是在自身末尾添加一个节点。在这种情况下没有任何意义。
  • 哦!我知道了!!你是救命稻草,非常感谢

标签: c algorithm linked-list


【解决方案1】:

给定一个指向头部的引用(指向指针的指针) 一个列表和一个int,在末尾插入一个新节点

void insertAtEnd(struct Node** head_ref, int new_data) 
{ 
    /* 1. allocate node */
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 

    /* 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 */
    struct Node *last = *head_ref;
    while (last->next != NULL) 
        last = last->next; 

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    相关资源
    最近更新 更多