簡體   English   中英

將數組作為鏈表存儲在C中

[英]storing an array as a linked list in C

我正在用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;
}

如果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中執行此操作的方法:

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM