【问题标题】:Making strcpy function with linked list in c在c中使用链表制作strcpy函数
【发布时间】:2015-01-27 21:05:06
【问题描述】:

我正在使用链表制作自己的 strcpy 函数,但不知道该怎么做。 不使用链表可能是这样的

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

但我不知道如何使用链表制作 strcpy。

【问题讨论】:

  • 为什么要使用链表来实现strcpy()?那里根本没有使用链接列表。
  • 注意:不能使用与库函数同名的函数。
  • @daniel Han “使用链表”是什么意思?
  • 这意味着使用自引用结构我试图在结构中接收字符串但无法获得如何

标签: c struct linked-list strcpy string.h


【解决方案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) &amp;&amp; (NULL != src_ptr)) --> 这是正确的

    while (NULL != *src_ptr) --> 这是错误的。

    请仔细检查数据类型。不要混淆variablepointer-to-variable

    【讨论】:

      猜你喜欢
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 2020-08-16
      • 2021-11-11
      • 2013-10-18
      • 2012-09-15
      相关资源
      最近更新 更多