链表不会给出预期的输出

链表不会给出预期的输出

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

问题描述

限时删除!!

这是链表的简单代码。在主要功能我试图打印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);

}

推荐答案

#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(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?


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

1403页,肝出来的..

09-06 12:30