程序目的是输出5个数的全排列,虽然有更简单的方法,但我用链表的方式来实行,目的是为了加深对链表的理解。
程序已经没有编译成功可运行。但是不能输出想要的结果,而且是死循环,希望高手们能给看一下。下面是代码:
#include <stdio.h>
#include <stdlib.h>
#include "intnode.h"
void main()
{
int a[5],i;
struct intnode *head,*p,*last,*current,*other;
void createintnode (struct intnode **,int);
struct intnode *insertnode (struct intnode **,struct intnode**,int);
for (i=0;i<5;i++)
scanf ("&d",a[i]);
head=NULL;
createintnode(&head,a[0]);
/*向链表中插入剩下的数据,用4层循环来产生全排列的所有情况*/
/*第一次循环,在第一个位置插入第一个数据,排列完后释放这个数据的空间,然后在第二个位置插入这个数据*/
for (current=head;;current=current->next){
other=insertnode (&head,¤t,a[1]);
/*第二次循环*/
for (current=head;;current=current->next){
other=insertnode (&head,¤t,a[2]);
/*第三次*/
for (current=head;;current=current->next){
other=insertnode (&head,¤t,a[3]);
/*第四次*/
for (current=head;;current=current->next){
other=insertnode (&head,¤t,a[4]);
p=head;
while(p!=NULL){
printf("%3d",p->data);
p=p->next;
getch();
}
free(other);/*删除插入的数据*/
if (current->next==NULL) break;
}
free(other);
if (current->next==NULL) break;
}
free(other);
if (current->next==NULL) break;
}
free(other);
if (current->next==NULL) break;
}
getch();
}
void createintnode (struct intnode **headp,int n)/*创建第一个结点*/
{
struct intnode *p;
p=(struct intnode*)malloc(sizeof(struct intnode));
p->data=n;
p->next=NULL;
*headp=p;
}
struct intnode *insertnode(struct intnode **headp,struct intnode **current,int n)/*插入结点*/
{
struct intnode *other;
/*创建一个结点*/
other=(struct intnode *)malloc(sizeof(struct intnode));
other->data=n;
/*插入结点的几种可能*/
if ((*current)->next!=NULL)
/*链头*/
if (current==headp){/**/
other->next=*headp;
*headp=other;
}
/*链中*/
else{
other->next=(*current)->next;
(*current)->next=other;
}
/*链尾*/
else{
other->next=NULL;
(*current)->next=other;
}
return (other);
}
其中"intnode.h"的代码是
struct intnode{
int data;
struct intnode *next;
};
struct intnode *head;
先谢谢了。