C中键盘输入的链接列表

时间:2011-12-01 20:25:02

标签: c linked-list

我正在编写代码,该代码采用从用户输入的整数并创建链接列表,然后打印出列表。整数应该放在列表的前面。

我需要一些帮助,我不知道如何打印数字。
这是我的代码:

Node.h

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

#ifndef _nodes
#define _nodes

typedef struct node_s {
       int d;
       struct node_s *next;
} node1;

node1 list(int d);
node1 addbegin(int d, node1 *head);
node1 print(node1 *head);

#endif

node.c

#include "node.h"
#include <stdio.h>

node1 *list_nodes(int d){
    node1 *node;
    node=(node1*)malloc(sizeof(node1));
    node->d=d;
    node->next=NULL;
    return(node);
}

node1 init(node1 *head){
    head->next=NULL;
}

node1 addbegin_nodes(node1 *head, int d){
    node1 *newnode;
    newnode=(node1*)malloc(sizeof(node1));
    newnode=list_nodes(d);
    head->next=newnode;
    return(newnode);
}

node1 print_nodes(node1 *head){
    node1 *temp;
    temp=(node1*)malloc(sizeof(node1));
    for(temp=head->next;
        temp;
  temp=temp->next)
            printf("%d", temp->d);
    return (d);
}

MAIN.C

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

int main(int argc, char* argv[]) {
    node1 *head;
    node1 *start;
    int num;

    printf("Please enter integers: ");
    while(scanf("%d", &num)!=EOF){
            head=(node1*)malloc(sizeof(node1));
            list(head);
            int i=0;
            for(i=0;i>=0;i--){
                    addbegin(head, num);
                    print(head);
            }
            printf("\n");
            print(head);
    }
    return 0;
}

2 个答案:

答案 0 :(得分:0)

将print_nodes更改为

//recursive version
void print_nodes(node1 *head)
{
    if (head != NULL)
    {
        printf("%d\n", head->d);
        print_nodes(head->next);
    }
}

或者

// normal version
void print_nodes(node1 *head)
{
    node1 *temp = head;

    while (temp != 0)
    {
        printf("%d\n", temp->d);
        temp = temp->next;
    }
}

我现在不知道为什么这些方法应该返回任何内容,请在评论中澄清。

答案 1 :(得分:0)

node1 init(node1 *head){
    head->next=NULL;
}

定义为返回node1,但似乎没有return语句。这可能是你问题的一部分吗?