#include <stdio.h>
#include <string.h>
#include <malloc.h>
const char *map[] = { "", "", "abc",
"def", "ghi", "jkl", "mno", "pqrs", "tuv",
"wxyz"
};
struct List {
char *s;
struct List *next;
};
char ans[16];
void AddString(struct List **list, char *combination)
{
int len;
struct List *nw;
if (!combination) { return ; }
if (!len) { return ; }
nw = (struct List*)malloc(sizeof(struct List));
if (!nw) { return ; }
nw->s = strdup(combination);
nw->next = NULL;
if (*list == NULL) {
*list = nw;
} else {
nw->next = (*list)->next;
(*list)->next = nw;
}
}
void BackTrace(struct List **list, char *combination, int index, char *digits)
{
char digit;
int i;
if (index == strlen(digits))
{
AddString(list, ans);
}
else
{
digit = digits[index++];
for (i = 0; i < strlen(map[digit - '0']); i++)
{
*(combination++) = *(map[digit - '0'] + i);
BackTrace(list, combination, index, digits);
}
}
}
char **LetterCombination(char *digits, int *retSize) {
struct List *list = NULL;
struct List *pos, *head;
int sc = 0;
char **ss = NULL;
int i;
char combination[16] = { '\0' };
if (!digits || !retSize) { return NULL; }
if (strlen(digits)) {
BackTrace(&list, ans, 0, digits);
}
for (pos = list; pos != NULL; pos = pos->next) {
sc++;
}
printf("\r\nsc=%d", sc);
ss = (char**)malloc(sizeof(char*) * sc);
if (!ss) {
*retSize = 0;
return NULL;
}
for (i = 0; i < sc; i++) { ss[i] = NULL; }
*retSize = 0;
head = list;
while (head != NULL) {
pos = head;
head = head->next;
ss[(*retSize)++] = strdup(pos->s);
free(pos->s);
free(pos);
}
return ss;
}
int main(void)
{
char digits[] = "23";
int nStr = 0;
char **strings = NULL;
int i;
strings = LetterCombination(digits, &nStr);
if (!strings) { return -1; }
for (i = 0; i < nStr; i++) {
printf("\r\n%s", strings[i]);
}
return 0;
}
uj5u.com熱心網友回復:
void AddString(struct List **list, char *combination)
{
int len;
struct List *nw;
if (!combination) { return ; }
//if (!len) { return ; } //你的len在哪賦值的?
len = strlen(combination);
if (!len) { return ; }
nw = (struct List*)malloc(sizeof(struct List));
if (!nw) { return ; }
nw->s = strdup(combination);
nw->next = NULL;
if (*list == NULL) {
*list = nw;
} else {
nw->next = (*list)->next;
(*list)->next = nw;
}
}
供參考~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/91622.html
標籤:C語言
上一篇:哪位大神幫我看看我的程式到底哪兒的錯誤,程式功能:輸入一串字符,找到其中最長的單詞并輸出該單詞和單詞長度
下一篇:求大佬幫忙
