Making strcpy function with linked list in c

為{幸葍}努か 提交于 2019-12-12 04:36:19

问题


I was making my own strcpy function using linked list but couldn't get how to do. Without using linked list it could be like this

char* cp2014strcpy(char * dest_ptr, const char * src_ptr) {
    char* strresult = dest_ptr;

    if((NULL != dest_ptr) && (NULL != src_ptr)) {
        while (NULL != src_ptr) {
            *dest_ptr++ = *src_ptr++;
        }
        *dest_ptr = NULL;
    }

    return strresult;
}

but I couldn't get how to make strcpy using linked list.


回答1:


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

typedef struct node {
    char ch;
    struct node *next;
} LL_str;

LL_str *LL_new(char ch){
    LL_str *s = malloc(sizeof(*s));//check omitted
    s->ch = ch;
    s->next = NULL;
    return s;
}

LL_str *s_to_LL(const char *s){
    LL_str *top, *curr;
    if(!s || !*s)
        return NULL;
    curr = top = LL_new(*s);
    while(*++s){
        curr = curr->next = LL_new(*s);
    }
    return top;
}

LL_str *LL_strcpy(const LL_str *s){//LL_strdup ??
    LL_str *top, *curr;
    if(!s)
        return NULL;
    curr = top = LL_new(s->ch);
    s=s->next;
    while(s){
        curr = curr->next = LL_new(s->ch);
        s=s->next;
    }
    return top;
}

void LL_println(const LL_str *s){
    while(s){
        putchar(s->ch);
        s = s->next;
    }
    putchar('\n');
}

void LL_drop(LL_str *s){
    if(s){
        LL_drop(s->next);
        free(s);
    }
}

int main(int argc, char *argv[]){
    LL_str *s = s_to_LL("Hello world!");
    LL_str *d = LL_strcpy(s);

    LL_println(d);
    LL_drop(s);
    LL_drop(d);
    return 0;
}



回答2:


if((NULL != dest_ptr) && (NULL != src_ptr)) --> this is correct

while (NULL != *src_ptr) --> this is wrong.

Please check the data type carefully. Don't mix up variable and pointer-to-variable



来源:https://stackoverflow.com/questions/27201627/making-strcpy-function-with-linked-list-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!