【问题标题】:storing an array as a linked list in C在 C 中将数组存储为链表
【发布时间】:2014-03-29 02:17:25
【问题描述】:

我正在使用 C 语言,但遇到了一些麻烦。我需要在一个链表中存储一个字符数组(字符串)。换句话说,将字符串转换为链表。基本上,每个节点一个字符。例如字符串 dog\0,而不是在最后一个节点中存储一个空字符,它只会指向一个空指针来表示字符串的结尾…… d->o->g->NULL

建议很好,谢谢

int main(){
    char *string;
    string = malloc(sizeof(char)*100);
    strcpy(string,"cheese");

    node *list = NULL;
    list = createNode(string[0]);

    int i;
    for(i=1;i<strlen(string);i++){
        // this is where I'm stuck, the first char 'c'is in,
        // I'm guessing i wanna loop through and
        // store each char in a new node ? 
    }

    return 0;
}

node *createNode(char data){
    node *ptr = malloc(sizeof(node));

    if (ptr == NULL)
    {
        return NULL;
    }

    ptr->data = data;
    ptr->next = NULL;

    return ptr;
}

【问题讨论】:

  • 创建一个链表数据结构并将每个字符一次插入到链表中...
  • having some trouble?好吧,那到底是什么?
  • 请给我们一些代码,以便我们更好地帮助您。
  • 我不认为我真的可以一次插入每个字符。我正在从输入文件中读取,并且字符串可能包含许多字符
  • 将在一分钟内发布代码

标签: c arrays string linked-list nodes


【解决方案1】:

以下是如何在 C 中执行此操作:

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

struct node {
    node *next;
    char data;
};

node *createNode(char data, node *parent) {
    node *ptr=(node*)malloc(sizeof(node));
    if(ptr==NULL) {
        fprintf(stderr, "Memory allocation error.\n");
        exit(1);
    }
    if(parent!=NULL) parent->next=ptr;
    ptr->data=data;
    ptr->next=NULL;
    return ptr;
}

int main() {
    char str[]="cheese";

    // Store the string to the list
    node *first=NULL, *cur=NULL;
    for(int i=0, len=strlen(str); i<len; i++) {
        cur=createNode(str[i],cur);
        if(first==NULL) first=cur;
    }

    // Now print it out
    cur=first;
    while(cur!=NULL) {
        printf("%c\n", cur->data);
        cur=cur->next;
    }

    _getwch();
    return 0;
}

【讨论】:

  • 我实际上开始将我的代码修改为类似的东西。至少我在正确的轨道上。谢谢!
【解决方案2】:

如果 C++ 没问题,那么这是一个工作示例:

#include <iostream>
#include <list>
using namespace std;

int main() {
    char str[]="cheese", chr;

    // Store the string in the list
    std::list<char> clist;
    for (int i=0, len=strlen(str); i<len; i++)
        clist.push_back(str[i]);
    clist.push_back('\0');

    // Display the list
    do {
        chr=clist.front();
        cout<<chr<<endl;
        clist.pop_front();
    } while(chr);

    _getwch();
    return 0;
}

【讨论】:

  • 谢谢,但我对 C++ 一无所知,甚至对 C 更是如此……我知道他们有一个容器类,与 C 相比,使用链表更容易
猜你喜欢
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
  • 2021-11-08
相关资源
最近更新 更多