課題は、「リストの要素(1~10)をランダムに並べ替えた、新たなリストを作るプログラムを作成せよという課題です。」
実行例 処理前:12345678910
処理後:83421097635 のような感じです。
自分なりに考えて見たのですが、プログラムを実行すると動作が停止してしまいます。
どこが間違っているのかを指摘していただけないでしょうか?
プログラミングをならって10ヶ月くらいになりますが得意ではないです。だから、変なプログラムだと思います。ごめんなさい。
#include < stdio.h >
#include < stdlib.h >
#include <time.h>
struct list
{
int data;
struct list *next;
};
// リスト構造の先頭に新しいデータを追加する関数
struct list *add_list(int x, struct list *head)
{
struct list *new_head;
new_head = (struct list *)malloc(sizeof(struct list));
new_head->data = x;
new_head->next = head;
return new_head;
}
// リスト構造を表示する関数
void show_list(struct list *head)
{
if (head == NULL) // NULLポインタだったら改行のみ表示
{
printf("\n\n");
}
else {
printf("%d", head->data);
show_list(head->next); //再帰呼び出し
}
}
void random(struct list *head1, struct list *head2) {
static int count;
int num;
srand((unsigned)time(NULL));
num = rand() % 10;
if ((head2 + num)->data == 0) {
random(head1, head2);
}
else
{
(head1 + count)->data = (head2 + num)->data;
(head2 + num)->data = 0;
count++;
}
}
void main()
{
int i;
struct list *head1;
struct list *head2;
int num;
// int num_2;
head1 = (struct list *)malloc(sizeof(struct list));
head2 = (struct list *)malloc(sizeof(struct list));
head1 = NULL;
head2 = NULL;
head1 = add_list(10, head1);
head1 = add_list(9, head1);
head1 = add_list(8, head1);
head1 = add_list(7, head1);
head1 = add_list(6, head1);
head1 = add_list(5, head1);
head1 = add_list(4, head1);
head1 = add_list(3, head1);
head1 = add_list(2, head1);
head1 = add_list(1, head1);
head2 = head1;
printf("処理前:");
show_list(head1);
printf("処理後 : ");
for (i = 0;i <= 10;i++) {
random(head1, head2);
}
show_list(head1);
}