2013-06-27 67 views
0

1)我需要從文件中讀字符串和字符串轉換爲一個鏈表字符串轉換爲一個鏈表

所以......如果我在這個字符串「一些字符串」

閱讀

鏈表看起來像這樣

節點1 - 「S」

節點2 - 「O」

節點3 - 「M」

節點4 - 「e」 的

節點5 - NULL

node6 - 「S」

node7 - 「t」 的

node8 - 「R」

node9 - 「i」 的

node10 - 「n」

node11 - 「G」

node12 - NULL

NULL會爲 「」(空格)和 「\ 0」 空字符

發出最新最好的方式來實現這個..

typedef struct node 
{ 
// each node holds a single character 
char data; 

// pointer to next node in linked list 
struct node *next; 
} node; 

int i; 
char buffer[1032]; 

    FILE *ifp = fopen("file.txt", "rb"); 

    //read the first line of file 
    fscanf(ifp, "%s", buffer); 

node *myList = malloc(sizeof(node)); 

for(i = 0; i < strlen(buffer); i++) 
    /*I DON'T KNOW WHAT TO DO HERE!!!!*/ 

這裏我迷路了,或者,如果我完全錯了我的執行,請讓我知道

+1

請記住標記你的問題與你使用的語言(這可能是C或C++)。 – Barmar

+1

'/ *我不知道在這裏做什麼!!!! * /'?那麼,我會說,對於字符串中的每個字符,您需要創建並初始化節點,然後將列表的尾部指向新節點。 –

回答

0

你的fscanf(ifp, "%s", buffer);會在讀取「Some」後停止。我使用fgets()代替。並在手冊(man與fgets):

與fgets()從流 ,並將它們存儲在至多一個小於大小的字符讀取到緩衝器由s指向。讀取 在EOF或換行符後停止。如果讀取換行符,則將其存儲在緩衝區中 。 '\ 0'存儲在 緩衝區中的最後一個字符之後。

最後的'\ 0'可以方便地將緩衝區作爲字符串處理。 所以FILE *ifp = fopen("file.txt", "rb");後,我的代碼是:

fgets(buffer,1032-1,ifp); 
node *myList,*head,*pre = NULL; 

for(i = 0; buffer[i] != '\0' ; i++) { 
    myList = malloc(sizeof(node)); 
    myList->data = buffer[i]; 
    if(pre!=NULL) 
     pre->next = myList; 
    else 
     head = myList; 
    pre = myList; 
} 

while(head!=NULL) { 
    printf("%c\n",head->data); 
    head=head->next; 
} 
fclose(ifp); 

您實現存儲 '\ n' 和空間爲NULL,它的確定,當您更改

myList->data = buffer[i]; 

if(buffer[i]=='\n' || buffer[i]==' ') 
    myList->data = 0; 
else 
    myList->data = buffer[i]; 
0
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct node { 
    char data;   // each node holds a single character 
    struct node *next; // pointer to next node in linked list 
} node; 

int 
main(int argc, char* argv[]) { 
    int i; 
    FILE* fp = fopen("example.txt", "r"); 
    if (!fp) { 
     perror("fopen"); 
     exit(1); 
    } 

    node *top = NULL; 
    node *cur = NULL; 
    int c; 
    while ((c = fgetc(fp)) >= 0) { 
     node *item = malloc(sizeof(node)); 
     item->data = c; 
     item->next = NULL; 
     if (!cur) { 
      // first time, store top. 
      top = cur = item; 
     } else { 
      // chain nexts. 
      cur->next = item; 
      cur = item; 
     } 
    } 
    fclose(fp); 

    // print datas 
    cur = top; 
    while (cur) { 
     printf("%c\n", cur->data); 
     cur = cur->next; 
    } 

    // free datas 
    cur = top; 
    while (cur) { 
     node *item = cur->next; 
     free(cur); 
     cur = item; 
    } 
    return 0; 
}