将字符串转换为链接列表

时间:2013-06-27 00:00:35

标签: c list pointers linked-list malloc

1)我需要读取文件中的字符串并将该字符串转换为链接列表

所以......如果我读了这个字符串“Some String”

链接列表将如下所示

node1 - “S”

node2 - “o”

node3 - “m”

node4 - “e”

node5 - NULL

node6 - “S”

node7 - “t”

node8 - “r”

node9 - “i”

node10 - “n”

node11 - “g”

node12 - NULL

将为“”(空格)和“\ 0”空字符

发出NULL

实现这个的最好方法是什么..

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!!!!*/

我迷失了,或者如果我对我的实施完全错误,请告诉我

2 个答案:

答案 0 :(得分: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;
}

答案 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];