[英]Making strcpy function with linked list in c
我正在使用鏈表創建自己的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。
if((NULL != dest_ptr) && (NULL != src_ptr))
->這是正確的
while (NULL != *src_ptr)
->這是錯誤的。
請仔細檢查數據類型。 不要混淆variable
和pointer-to-variable
variable
pointer-to-variable
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.