回复 10楼 beyondyf
大哥~~~麻烦你解释一下啊~~~~~麻烦咯~~
再复杂的问题也基于最简单的原理。耐心,耐心!丰富自己!等待时机!
#include<stdio.h> #include<malloc.h> #define CAPACITY_DEFAULT 1024 #define CAPACITY_GROWTH 1024 typedef char DATA; typedef struct { DATA *data; int length; int capacity; }LIST; LIST * creat_list() { LIST * list; list = (LIST *)malloc(sizeof(LIST)); list->data = (DATA *)malloc(CAPACITY_DEFAULT * sizeof(DATA)); list->length = 0; list->capacity = CAPACITY_DEFAULT; return list; } void delete_list(LIST * list) { free(list->data); free(list); } int isValid(DATA value) { return value >= 'a' && value <= 'z' || value >= 'A' && value <= 'Z'; } void clear_list(LIST * list) { list->length = 0; } void insert_data(LIST * list, DATA value, int index) { int i; DATA * p; if(!isValid(value) || index < 0 || index > list->length) return; if(list->length >= list->capacity) { list->capacity += CAPACITY_GROWTH; p = (DATA *)malloc(list->capacity * sizeof(DATA)); memcpy(p, list->data, sizeof(DATA) * index); p[index] = value; memcpy(p + index + 1, list->data + index, (list->length - index) * sizeof(DATA)); free(list->data); list->data = p; list->length++; return; } for(i = list->length; i > index; i--) list->data[i] = list->data[i - 1]; list->data[index] = value; list->length++; } void append_data(LIST * list, DATA value) { insert_data(list, value, list->length); } void delete_data(LIST * list, int index) { int i; if(index <= 0 || index >= list->length) return; for(i = index; i < list->length; i++) list->data[i] = list->data[i + 1]; list->length--; } void print_list(LIST * list) { int i; for(i = 0; i < list->length; i++) printf("%c", list->data[i]); } int main() { char str[128]; int i; LIST * list; list = creat_list(); printf("测试输入一串字符:\n"); scanf("%s", str); for(i = 0; str[i] != '\0'; append_data(list, str[i++])); print_list(list); printf("\n"); printf("测试插入字符,格式:索引(从0开始) 字符\n"); scanf("%d %c", &i, str); insert_data(list, str[0], i); print_list(list); printf("\n"); printf("测试删除字符,格式:索引(从0开始)\n"); scanf("%d", &i); delete_data(list, i); print_list(list); printf("\n"); delete_list(list); return 0; }