如何更改代码以使输出等于节点中的所有数据元素?

时间:2017-10-30 20:23:47

标签: c

我今天学会了链表,并尝试了这段代码。我想使用for循环将5个输入值添加到列表中。在for循环的底部,“head = head-> next” 将头指针前进到列表中的下一个节点,当循环终止时,列表中的最后一个节点将其.next字段设置为NULL以标记列表的结尾,然后使用while循环输出列表。但是当我编译并运行代码时,列表的输出值并不相同!作为输入值。我在哪里错了?

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

    struct node{
    int data;
    int key;
    struct node* next;
    };

    struct node* head=NULL;


    int main(){

    int i;
    int a;
    int b;
    head=(struct node*)malloc(sizeof(struct node));//allocated memory

    for(i=0;i<5;i++){
    scanf("%d %d",&a,&b);
    head->data=a;
    head->key=b;
    head->next=(struct node*)malloc(sizeof(struct node));
    head=head->next;
    }
    head->next=NULL;

    int j;
    struct node* m;
    m=head;


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

        }

    } 

2 个答案:

答案 0 :(得分:1)

这是在链表末尾进行插入的方式:

void insertend(int a,int b)
        {
            current=head;
            struct list * temp=(struct list*) malloc(sizeof(list));
            temp->data=a;
            temp->key=b;
            temp->next=NULL;
            while(current->next!=NULL)
            current=current->next;
            current->next=temp;
            current=temp;
        }

答案 1 :(得分:0)

请参阅以下代码中的评论,并尝试了解您的错误。这也不是您创建链接列表并在其中添加节点的方式。

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

struct node{
int data;
int key;
struct node* next;
};

struct node* head=NULL;


int main(){

int i;
int a;
int b;
head=(struct node*)malloc(sizeof(struct node));//allocated memory
//above you have create a node and head is pointing to it
for(i=0;i<5;i++){
    scanf("%d %d",&a,&b);
    head->data=a;
    head->key=b;
    head->next=(struct node*)malloc(sizeof(struct node));
    //till above code it was find
    head=head->next;//but here you did the mistake, now head it pointing to the newly created node and you lost the address of first node
    //finally when you created the list with 5 nodes head is actually pointing to the last node of the list
  //hence it will print only the last node of the list
}
  //now do some modification and rewrite the for loop like below
/*
 struct node* p=head;
 for(i=0;i<5;i++){
    scanf("%d %d",&a,&b);
    p->data=a;
    p->key=b;
    p->next=(struct node*)malloc(sizeof(struct node));
    p=p->next
} */

// head->next=NULL; //also change this line with below line of code
  p->next = NULL;    
 int j;
 struct node* m;
 m=head;
    while(m!=NULL){
        printf("%d %d ",m->data,m->key);
        m=m->next;
    }
}