注册 登录
编程论坛 C语言论坛

有大佬知道为什么我的链表输出不正确吗

铁甲 发布于 2020-11-29 17:17, 1260 次点击
程序代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct _node{
    int value;
    struct _node *previous;
    struct _node *next;
} Node;
int main(void){
    Node *head=NULL;
    Node *tail=NULL;
    int j=1;
    for(int number;scanf("%d",&number)==1&&number!=-1;){
        Node *Last=head;
        if(j==1){
            head=(Node *)malloc(sizeof (Node));
            head->value=number;
            head->next=NULL;
            head->previous=NULL;
            j++;
            break;
        }
        else{
        for(;Last;Last=Last->next);
            Node *p=(Node *)malloc(sizeof (Node));
            Last->next=p;
            p->value=number;
            p->next=NULL;
            p->previous=Last;
            tail=p;
        }
        }
    for(Node *i=head;i;i=i->next){
          printf( "%d\t", i->value );
    }   
    for(Node *k=tail;k;k=k->previous){
          printf( "%d\t", k->value );
    }   
    return 0;
    }
   
1 回复
#2
rjsp2020-11-30 09:07
程序代码:
#include <stdio.h>
#include <stdlib.h>

typedef struct _node {
    int value;
    struct _node* previous;
    struct _node* next;
} Node;

int main( void )
{
    Node* head = NULL;
    Node* tail = NULL;
    for( int number; scanf("%d",&number)==1 && number!=-1; )
    {
        Node* p = malloc(sizeof(Node));
        p->value = number;
        p->next = NULL;

        if( !tail )
        {
            p->previous = NULL;
            head = tail = p;
        }
        else
        {
            p->previous = tail;
            tail->next = p;
            tail = p;
        }
    }

    for( const Node* p=head; p; p=p->next )
        printf( "%d\t", p->value );

    for( const Node* p=tail; p; p=p->previous )
        printf( "%d\t", p->value );
}
1