在双向链表的末尾插入

时间:2015-08-12 05:29:48

标签: c data-structures

我只能查看输入的第一个元素。代码如下:

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

typedef struct d_list{
    int data;
    struct d_list *next;
    struct d_list *prev;
}node;

//没有递归调用insert函数。

typedef node *list;
main(){
    printf("Enter data(y/n)?");
    char ch;
    scanf("%s",&ch);
    int n;
    list head;
    list temp;
    list tail;
    head=tail=temp=NULL;
    if(ch=='y'||ch=='Y'){
        printf("Enter data");
        scanf("%d",&n);
        temp=(list)malloc(sizeof(node));
        temp->data=n;
        temp->next=temp->prev=NULL;
        head=temp;
        tail=temp;
    }
    printf("Enter more data..?(y/n)");
    scanf("%s",&ch);
    while(ch=='y'||ch=='Y'){
        printf("Enter data");
        scanf("%d",&n);
        temp=(list)malloc(sizeof(node));
        temp->data=n;
        temp->prev=tail;
        temp->next=NULL;
        tail->next=temp;
        tail=temp;
        printf("Enter more data..?(y/n)");
        scanf("%s",&ch);
    }

    temp=head;
    while(temp!=NULL){
        printf("%d",temp->data);
        temp=temp->next;
    }
    getch();
}

我想按照输入的顺序显示所有输入。这里有什么问题?

2 个答案:

答案 0 :(得分:2)

您的代码逻辑是正确的,但错误如下:将scanf("%s",&ch);设为scanf(" %c",&ch);

答案 1 :(得分:0)

尝试这个最简单的问题代码,我所做的更改,

  

更改了scanf(“%s”,&amp; ch); to scanf(“%c”,&amp; ch);

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

#define _CRT_SECURE_NO_WARNINGS

using namespace std;
typedef struct d_list{
    int data;
    struct d_list *next;
    struct d_list *prev;
}node; 

typedef node *list;
int main()
{
    char ch;
    int n;
    list head = NULL,temp = NULL,tail = NULL;  
    do{
        printf("\nEnter data ?(y/n):\n");
        scanf("%c",&ch); 
        if(ch=='n'||ch=='N')
            break;
        printf("\nEnter data :\n");
        scanf_s("%d",&n);
        temp=(list)malloc(sizeof(node));
        temp->data=n;
        temp->next=NULL;
        if(head == NULL)
        {  
            temp->prev=NULL;
            head=temp; 
        }
        else
        {
            temp->prev=tail;
            tail->next=temp;
        }
        tail=temp;  
    }while(ch=='y'||ch == 'Y');

    temp=head;
    while(temp!=NULL){
        printf("\n%d",temp->data);
        temp=temp->next;
    } 
    getch();
    return 0;
}
相关问题