2014-11-08 13 views
1

我已經設置了一個賦值來將文本行存儲到鏈接列表中的句點並顛倒它們的順序,而不打印句號。將文本行存儲爲鏈接列表,然後在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 

任何人都可以幫助我什麼我的代碼部分造成的?

+1

爲什麼不使用像'fgets'和'strcpy'這樣的標準庫函數?你的字符串'l'不是空終止的。它也容易發生緩衝區溢出。另一個錯誤是,你不需要在開始時爲頭部分配內存 - 一個空列表是一個擁有'head == NULL'的列表。爲了完整起見,您應該在最後釋放分配的內存。 – 2014-11-08 18:47:09

+0

@MOehm我被告知使用getchar()進行分配,感謝您的幫助 – user2412643 2014-11-08 18:51:35

+0

好的,我明白了。 (使用'getchar'沒有錯,只是稍微複雜一點,這可能是練習的一部分。)爲了解決你的問題,刪除循環前的第一個'calloc'。在'while'之後,添加一個終止空字符:'l [i] ='\ 0';'。 – 2014-11-08 18:55:27

回答

0

用'\ 0'關閉字符串,否則strlen和pals將無法計算出實際大小。新行'\ n'存儲在字符串中,但是頭部有一個額外的'。'。處理。

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); 
} 
相關問題