Frage

I'm working in C and am having some trouble. I need to store an array of chars (string) across a linked list. In other words, convert a string to a linked list. Basically, one character per node. For example string, dog\0, rather then storing a null character in the last node it would just point to a null pointer to signify the end of the string…… d->o->g->NULL

An suggestions would be great, thank you

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;
}
War es hilfreich?

Lösung

Here is how to do this in 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;
}

Andere Tipps

If C++ is OK then here is a working sample:

#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;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top