微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

下面双链表中的指针问题如何解决?

如何解决下面双链表中的指针问题如何解决?

最近学习了双向链表,并尝试用C编写一些代码来实现它们。下面的程序应该接收来自用户的整数输入,并将它们放入一个最多包含十个整数的列表中。但是,当我输入值然后打印它们时,只输出一个和最后一个值。人们将如何解决这个问题? 代码如下:

`#include <stdio.h>
#include <stdlib.h>
struct node {
    struct node* prev;
    int num;
    struct node* next;

};


struct node *head,*p;
struct node* create_first_node(int x)
{
    struct node *new = (struct node*)malloc(sizeof(struct node));
    new->num=x;
    new->prev=NULL;
    new->next=NULL;
    head=new;
    p=head;
    return new;
}
void add_node(int x)
 {
    struct node*new=(struct node*)malloc(sizeof(struct node));
    new->num=x;
    new->prev=p;
    p->next=new;
    (new->next)=NULL;
    new=p;
 }

 void print_list(){
    struct node *temp= head;
    printf("\nThe list is:\n");
    while (temp!=NULL)
    {
        printf("%d\t",temp->num);
        temp=temp->next;
    }
}

int main(){
    int in[10];
    int len,i;
    head=NULL;
    
    printf("How many nodes would you like?(Max=10) \n");
    scanf("%d",&len);

    for (i = 0; i < len; i++)
    {
         if (head == NULL && i==0)
        {   
            printf("Enter Value for node %d\n",i+1);
            scanf("%d",(in+i));
            create_first_node(in[0]); 
           
        }
        else
        {
                printf("Enter Value for node %d\n",i+1);
                scanf("%d",(in+i));
                add_node(in[i]);
        }
        
    }
    
   
    print_list(head);
    return 0;
}`

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。