【问题标题】:Insert in a Linked List : Bug插入链接列表:错误
【发布时间】:2014-08-31 15:12:17
【问题描述】:

在下面的代码中:插入函数不能插入超过 2 个节点。

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

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

struct node * insertl(struct node * head,int value)
{
   if(head==NULL)
  {
     struct node * temp= malloc(sizeof(struct node));
     temp->val = value;
     temp->next=NULL;
     head=temp; printf("%d",value);
     return head;
 }
 if(head->next==NULL)
 {
    struct node * temp= malloc(sizeof(struct node));
    temp->val = value;
    temp->next=NULL;
    head->next = temp; printf("%d",value);
    return head;
 }
 struct node *head1=head;
 while(!head1->next)
 {
    head1=head1->next;
    printf("%d",head1->val);
 }

 struct node * temp= malloc(sizeof(struct node));
 temp->val = value;
 temp->next=NULL;
 printf("%d",temp->val-90);
 head1->next = temp;
 return head;
 }

  void print(struct node *head)
{     printf("\n");
   struct node * temp = head;
   while(temp!=NULL)
  {
    printf("%d\t",temp->val);
    temp=temp->next;
   }

 }

int main()
{   struct node * h =NULL;
    h=insertl(h,1);
    h=insertl(h,4);
    h=insertl(h,1);
    h=insertl(h,4);
    print(h);
 }

我在中间使用了 printf 语句来检查代码出错的地方。 输出显示:1,4。为什么代码不正确?

【问题讨论】:

    标签: c algorithm insert linked-list


    【解决方案1】:
    struct node *head1=head;
    while(!head1->next)
          ^
    

    我认为您正在尝试追加到列表的“末尾”,您的意思是while(head1-&gt;next)

    【讨论】:

    • 非常感谢您这么快的回复。我觉得很糟糕,很粗心
    猜你喜欢
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多