从用户链接列表中扫描字符

问题描述

我应该编写一个函数来扫描来自用户的输入直到输入并将其输入到链表中。 我不能把它扫描成一个字符串,然后把它放在一个列表中。

我写了这段代码,没有将字符输入到链表中,也没有从控制台退出,直到我按下退出。

typedef struct chNode
{
    char data;
    struct chNode *next;
}chNode;


chNode * createCharList(char data)
{
    chNode *temp = (chNode*)malloc(sizeof(chNode));
    temp->data = data;
    temp->next = NULL;
    return temp;
}

chNode * addCharToLast(chNode *head,char data)
{
    chNode *p = head;
    chNode *temp = createCharList(data);
    if (head == NULL)
        return temp;
    while (p->next != NULL)
        p = p->next;
    p->next = temp;
    return head;
}


chNode* insert_Charlist() 
{
    char ch;
    chNode *Head = NULL;
    printf("Enter chars For Linked-List Till 'Enter':\n");
    scanf_s("%c",&ch);
    while (ch != '\n')
    {

        Head = addCharToLast(Head,ch); 
        scanf_s("%c",&ch);
        
    }
    return Head;
}

void main()
{

    chNode *Orignial_list = NULL;
    Orignial_list = insert_Charlist(); // Function that imports a list
    printf("You Entered This linked-list:\n");
    printf_CharList(Orignial_list); //Printing the linked list
    
    getch();

}

解决方法

对于 scanf 的这个调用

scanf_s("%c",&ch);

您需要再指定一个参数

scanf_s( "%c",&ch,1 );

您通过调用函数 insert_Charlist 来实现函数 addCharToLast 的方法效率低下,因为每次添加新字符时,函数 addCharToLast 都会遍历整个列表清单。

我可以建议以下函数实现,如下面的演示程序所示。

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

typedef struct chNode
{
    char data;
    struct chNode *next;
} chNode;

chNode * createNode(char data )
{
    chNode *temp = (chNode*)malloc( sizeof( chNode ) );
    
    if ( temp != NULL )
    {
        temp->data = data;
        temp->next = NULL;
    }
    
    return temp;
}

size_t insert_Charlist( chNode **head ) 
{
    while ( *head ) head = &( *head )->next;
    
    size_t n = 0;
    
    printf( "Enter chars For Linked-List Till 'Enter': " );

    for ( int data; ( data = getchar() ) != EOF && 
                    data != '\n' && 
                    ( *head = createNode( data ) ) != NULL; )
    {
        head = &( *head )->next;
        ++n;
    }
    
    return n;
}

void printf_CharList( const chNode *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%c -> ",head->data );
    }
    
    puts( "null" );
}

int main(void) 
{
    chNode *head = NULL;
    
    insert_Charlist( &head );
    
    printf_CharList( head );
    
    return 0;
}

程序输出可能看起来像

Enter chars For Linked-List Till 'Enter': Hello
H -> e -> l -> l -> o -> null

注意,根据C标准,没有参数的函数main应该声明为

int main( void )

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...