簡體   English   中英

將文本行存儲為鏈接列表,然后在C中顛倒其順序

[英]Store lines of text as a linked list then reverse their order in C

我已被分配一個任務,以將文本行最多存儲到鏈接列表中的句點並顛倒其順序,而無需打印句點。

到目前為止,我的代碼是:

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

struct node {
   char line[50];
   struct node *next;
};

int main()
{
   //intialise stuff
   char l[50];
   int i;
   struct node *head = NULL, *newNode, *current;
   head = (struct node *)calloc(1,sizeof(struct node));
   char c;

   //read in list reversed
   printf("Enter some lines followed by '.':\n");
   while(c!='.'){
      i=0;
      do {
         c = getchar();
         if (c != '.') {
            l[i]=c;
            i++;
         }
         else
            {break;}
         } while (c!='\n');

      newNode = (struct node *)calloc(1,sizeof(struct node));
      for (i=0;i<strlen(l);i++)
         newNode->line[i] = l[i];
      newNode->next=head;
      head = newNode;
   }



   //print reversed list
   current = head;
   while (current != NULL) {
        for (i=0;i<strlen(current->line);i++)
        printf("%c", current->line[i]);
        current = current->next;
   }
   return 0;
}

該代碼適用於以下輸入:

hello

there

world.

但是當我輸入

1234

4321

7777.

輸出具有與

  00

  01

超過第一個數字,並且如果我輸入:

ricky

is

cool.

輸出為:

cooly

is

ky

ricky

誰能幫我解決我代碼的哪部分造成這種情況?

用'\\ 0'閉合字符串,否則會拉長,​​並且好朋友將無法計算出實際大小。 新行'\\ n'存儲在字符串中,但是head附加了一個'。'。 處理。

const uint SZ = 50;
struct node { struct node * next; char line[SZ]; };
struct node * wnod, * head = 0;
uint idx;
char ch = '\n';
// read in list reversed
printf( "Enter some lines followed by '.':\n" );
while( '.' != ch )
{
    wnod = ( struct node * ) calloc( 1, sizeof( struct node ) );
    wnod->next = head;
    for( idx = 0; idx < SZ - 1; ++idx )
    {
        ch = getchar();
        if( ( '.' != ch ) && ( '\n' != ch ) )
        { 
                    wnod->line[idx] =   ch;
        } else {    
                    wnod->line[idx] = '\0'; idx = SZ;
        }
    }
    head = wnod;
}
// print linked list
while( head )
{
    for( idx = 0; idx < strlen( head->line ); ++idx )
    {
        printf( "%c", head->line[idx] );
    }
    printf( "|\n" );
    wnod = head; head = head->next; free( wnod );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM