C 练习实例1

C 练习实例1

使用递归与链表:

#include

#define NUM 4 // 数字个数

#define LEN 3 // 排列出的数字的长度

struct number {

int val;

struct number *next;

} list[NUM];

void permutation(struct number *list, int m)

{

static int array[LEN];

struct number *p, *piror, *head;

if(m) // 如果此次还未排列好,则选择剩余数字继续排列

for(piror=NULL, p=list, head=list; p; piror=p, p=p->next)

{

array[LEN - m] = p->val; // 将排列结果临时存入数组

if(piror) // 如果本次选择的数字不在表头

{

piror->next = p->next; // 重组链表进行下一位数的排列

permutation(head, m-1);

piror->next = p; // 还原链表

}

else permutation(p->next, m-1);

}

else // 否则打印出此次排列出的数字

{

int i;

for(i=0; i

printf("%d%c", array[i], i==LEN-1? '\n': ',');

}

}

int main()

{

int i;

// 初始化链表

for(i=0; i

{

list[i].val = i + 1;

list[i].next = list + i + 1;

}

list[NUM - 1].next = NULL;

// 递归打印排列结果

permutation(list, LEN);

return 0;

}

递归排列的过程中逐一将选中的数字从链表中删除,直接避免组成的三位数中出现重复数字。

大宅院里的三表哥 大宅院里的三表哥

gul***r@outlook.com

3年前 (2022-09-07)