含重复字符的字符串全排列问题
当输入字符在1至4个之间 运行结果正常
当输入字符在5个或5个以上时 运行就要弹个对话框出来 说什么某内存地址不能为读还是不能为写哦 具体记不清了 我在网吧
多谢各位指点
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sum = 0; /* 全排列个数 */
int iLength = 0; /* 字符串才长度 */
struct node
{
char *string;
struct node *next;
};
struct node *head, *pCurNode;
void insert(char *pStr)
{
struct node *ptmp;
int i;
char *pCurStr;
pCurStr = (char *)malloc(strlen(pStr) + 1);
strcpy(pCurStr, pStr);
if(sum == 0)
{
ptmp = (struct node *)malloc(sizeof(struct node));
if(ptmp == NULL)
{
printf("malloc error!\n");
return;
}
ptmp->string = pCurStr;
ptmp->next = NULL;
head = ptmp;
pCurNode = head;
sum++;
}
else
{ /* 检查有无重复字符 */
ptmp = head;
for(i=0; i<sum; i++)
{
if(!strcmp(ptmp->string, pCurStr))
{
printf("Have same string: %s\n", pCurStr);
return;
}
ptmp = ptmp->next;
}
/* 无重复字符,插入存储链表 */
ptmp = (struct node *)malloc(sizeof(struct node));
if(ptmp == NULL)
{
printf("malloc error!\n");
return;
}
ptmp->string = pCurStr;
ptmp->next = NULL;
pCurNode->next = ptmp;
pCurNode = ptmp;
sum++;
}
}
/* 把字母从小到大排序 */
void compositor(char *pStr)
{
char temp;
int i, j;
for(i=0; i<iLength-1; i++)
for(j=i+1; j<iLength; j++)
if(pStr[i] > pStr[j])
{
temp = pStr[i];
pStr[i] = pStr[j];
pStr[j] = temp;
}
printf("Now, the string is %s\n", pStr);
}
void Permute(char in[], char out[], int used[], int recursLev)
{
int i;
if(recursLev == iLength)
{
insert(out);
}
for(i = 0; i < iLength; i++)
{
if(used[i]) /* 如果这个字母已经使用,则跳到下一个字母 */
continue;
out[recursLev] = in[i]; /* 把这个字符填充入out序列 */
used[i] = 1; /* 标记这个字母已经被使用 */
Permute(in, out, used, recursLev+1);
used[i] = 0; /* 取消字母标记 */
}
}
int Init(char *inString)
{
int i, *ipUsedFlag;
char *cpOut;
cpOut = (char *)malloc(iLength + 1);
if(!cpOut)
return 0;
cpOut[iLength] = '\0';
ipUsedFlag = (int *)malloc(sizeof(int) * iLength);
if(!ipUsedFlag)
return 0;
for(i = 0; i < iLength; i++) /* 初始化ipUsedFlag */
{
ipUsedFlag[i] = 0;
}
Permute(inString, cpOut, ipUsedFlag, 0);
free(cpOut);
free(ipUsedFlag);
return 1;
}
void main()
{
char Str;
struct node *p;
int i;
printf("Please input the string:\n");
gets(&Str);
iLength = strlen(&Str);
compositor(&Str); /* 可以不要,只是为了好看 */
Init(&Str);
/* 输出所有排列 */
p = head;
for(i = 1; i <=sum; i++)
{
printf("%d : %s\n", i, p->string);
p = p->next;
}
}
问题点数:20、回复次数:5Top
1 楼Sniper167(啥都不会)回复于 2006-05-04 09:49:54 得分 0
难道是分不够???
另外开开帖再加就是。。。Top
2 楼xombat(壞牧羊人)回复于 2006-05-04 13:07:25 得分 0
当输入字符在5个或5个以上时 运行就要弹个对话框出来 说什么某内存地址不能为读还是不能为写哦
=======================================
按你说的,应该是数组访问越界,或是指针的问题,好好看看你的指针和数组变量吧。
分少,没时间看。Top
3 楼xombat(壞牧羊人)回复于 2006-05-04 13:07:37 得分 0
抱歉。Top
4 楼san_126(阿三)回复于 2006-05-04 15:05:16 得分 20
// 将main()函数中做一下修改便好了
void main()
{
char Str[50]; //////表示修改了的地方
struct node *p;
int i;
printf("Please input the string:\n");
gets(Str); //////表示修改了的地方
iLength = strlen(Str); //////表示修改了的地方
compositor(Str); /* 可以不要,只是为了好看 */ //////表示修改了的地方
Init(Str);//////表示修改了的地方Top
5 楼Sniper167(啥都不会)回复于 2006-05-04 21:08:58 得分 0
原来是分少的原因 下次多给点 ^_^Top




