链表不会给出预期的输出。 [英] Linked list doesn't give the expected output.

查看:76
本文介绍了链表不会给出预期的输出。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是链表的简单代码。在主要功能我试图打印2和3,但代码只打印最后一个值,即3.我没有得到代码的错误。这是代码

This is simple code of linked list . In the main function i am trying to print 2 and 3 but the code prints only last value i.e 3. I am not getting what is wrong with the code . Here is the code

#include<stdio.h>

struct list {
  int data;
  struct list *next;
};

  struct list* insert(struct list* node,int data)
  {
    struct list* newnode=malloc(sizeof(struct list));
    if(!newnode){
      newnode=data;
    }
    newnode->data=data;
    newnode->next=NULL;
  }

printlist(struct list* node)
{
  struct list *newnode;
  if(!newnode)
    {
      printf("empty list\n");
    }
  while(newnode!=NULL)
    {
      printf("%d\n",newnode->data);
      newnode=newnode->next;
    }
}


int main()
{
   int i,n;
  struct list* temp;
  temp=malloc(sizeof(struct list));
  for(i=0;i<9;i++){
    scanf("%d",&n);
    insert(temp,n);
  }
   
 printlist(temp);

}

推荐答案

您的代码中有很多错误。

以下一个有效的实施。然而,就目前而言,它仍然相当丑陋:你必须完成(例如你需要最终释放内存)并改进它。



There are many errors in your code.
Below a working implementation. However, as it stands, it is still rather ugly: you have to complete (for instance you need to eventually release the memory) and improve it.

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

struct list {
  int data;
  struct list *next;
};

struct list* insert(struct list* node,int data)
{
  struct list* newnode=malloc(sizeof(struct list));
    assert(newnode);
  newnode->data=data;
  newnode->next=NULL;
    if( node )
    {
        while ( node->next )
            node = node->next;
        node->next = newnode;
    }
    return newnode;
}

void printlist(struct list* node)
{
  if(!node)
  {
    printf("empty list\n");
  }
  while(node!=NULL)
  {
    printf("%d\n",node->data);
    node=node->next;
  }
}


int main()
{
  int i,n;

  struct list * first;

    scanf("%d",&n);

    first= insert(NULL,n);

  for(i=1;i<9;i++){
    scanf("%d",&n);
    insert(first,n);
  }

 printlist(first);

}


查看您的代码:如果没有别的,请仔细查看printlist:

Look at your code: if nothing else, have a close look at printlist:
printlist(struct list* node)
{
  struct list *newnode;
  if(!newnode)
    {
      printf("empty list\n");
    }
  while(newnode!=NULL)
    {
      printf("%d\n",newnode->data);
      newnode=newnode->next;
    }
}

你在哪里使用传入的节点?那么您希望它如何打印它包含的值?

Where in there are you using the "node" you pass in? So how would you expect it to print the values it contains?


这篇关于链表不会给出预期的输出。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆