【问题标题】:display function Link-list code not working显示功能链接列表代码不起作用
【发布时间】:2016-07-27 16:59:33
【问题描述】:

我试图在链表的开头添加节点,但在我的代码中它只显示最后一个元素,我只输入了最后一个元素。这是什么问题,为什么会发生这种情况

 #include <stdio.h>
//node structure
struct node
{
    int data;
    struct node *next;

};

//结构

//datatype declaration 
typedef struct node node ;
// head pointer which will indicate starting point of link list
node *head;

//create fuction that will insert values into note and its next pointer field 
void create(int num);
//display function will display the link list 
void display();

main()
{

        int num,i,n;

        printf("enter the nno of node to create : ");
        scanf("%d",&n);

        for(i=0;i<n;++i)
        {
            printf("enter data for node %d= ",i+1);
            scanf("%d",&num);
            create(num);



        }
        display();

//显示调用

}
void create(int num)
{
        head=NULL;
        node *temp;
        temp=(node*)malloc(sizeof(node));
        temp->data=num;
        temp->next=head;
        head=temp;




return;
}

//函数create()结束

void display()
{
    node *temp1;
    temp1=head;

     while(temp1!=NULL)
    {
        printf("data : %d-> ",temp1->data);
        temp1=temp1->next;


    }

return;
}

//函数显示()结束

【问题讨论】:

    标签: singly-linked-list


    【解决方案1】:

    你的主要问题是:

    head=NULL;
    

    所以你的线

    temp->next=head;
    

    总是将下一个设置为NULL。因此,您的所有清单都是 长度为一。

    我建议将 head 声明为 static(并且 因此从一开始就归零),或在main 中初始化head。

    【讨论】:

      【解决方案2】:

      您的显示功能看起来不错,您的创建功能应该如下所示:

          void create(int num)
      {
      node* temp = new node();
      
              if(head ==NULL)
      
              { temp->data = num;
                head = temp;
                head->next =  NULL;
              }
             else if(head->next == NULL)
             {
               temp->data = num;
               head->next = temp;
              }
            else
            {
              node* temp2 = head;
              while(temp2->next !=NULL)
              { temp2 = temp2->next;
              }
              temp->data = num;
              temp2->next = temp;
            }
      
      
      
      return;
      }
      

      上面的这个创建函数将根据列表是空的、有一个节点还是多个节点插入到最后一个位置来放置节点。您现在可以关闭它以在头部前面插入,或在链接列表术语功能 (InsertBeforeFirst) 中插入。当然,如果你有 node* head up top 应该初始化为 NULL;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-21
        • 1970-01-01
        • 2021-06-29
        • 1970-01-01
        • 1970-01-01
        • 2018-05-13
        • 1970-01-01
        • 2021-08-23
        相关资源
        最近更新 更多