ページ 11

要素の挿入

Posted: 2017年5月15日(月) 12:40
by 連結リストわからない
今日から連結リストの単元に入りました。このようなプログラムが与えられて、
3番目の要素の前に新しい要素を挿入し、その値を100として再び要素の値を出力せよ
という課題が出ました。
図で説明されたので、どういうことをすればいいのかは理解できましたが、コードに関しては全く分かっていない状態です。

どなたかわかりやすく教えていただけないでしょうか?
よろしくお願いします。

コード:

/////////////////////////////////////////////
//N個整数を格納する連結リストを作成せよ。
/////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>

//10個の要素を生成する。適当に変更してもよい
#define N 10

//連結リストの要素を表す構造体を定義する
struct cell {
	int data;
	struct cell *next;
};

//簡潔に書けるため、型を定義する
typedef struct cell Cell;

void main(void)
{
	int i;
	
	Cell *head, *p;
	

	head = (Cell *)malloc(sizeof(Cell));
	
	
	(*head).data = 10+(int)(rand()*
		(50-10+1.0)/(1.0+RAND_MAX));


	p = head;


	for(i=1;i<N;i++){
		
		(*p).next = (Cell *)malloc(sizeof(Cell));

		
		p = (*p).next;

		
		p->data = 10+(int)(rand()*
			(50-10+1.0)/(1.0+RAND_MAX));
	}
	
	p->next = NULL;
	
	
	p = head;
	

	while(NULL != p){
		
		printf("data = %d\n",(*p).data);

		
		p = p->next;
	}
	
	return;
}

Re: 要素の挿入

Posted: 2017年5月15日(月) 17:31
by かずま
head は 1番目の Cell を指していますよね。

コード:

	p = head->next; // p は 2番目のセルを指す

	q = (Cell *)malloc(sizeof(Cell)); // q は 新しいセルを指す
	q->data = 100;      // 新しいセルにデータを入れる
	q->next = p->next;  // 新しいセルに、元の 3番目以降をつなぐ
	p->next = q;        // 2番目のセルに新しいセルをつなぐ
理解できますか?
これを参考に、プログラム全体を書き直して貼り付けてください。
無駄な空行はつけないでほしい。
できれば、何番目にでも挿入できる汎用的なコードにしてください。

Re: 要素の挿入

Posted: 2017年5月26日(金) 07:33
by かずま
かずま さんが書きました:理解できますか?
これを参考に、プログラム全体を書き直して貼り付けてください。
無駄な空行はつけないでほしい。
できれば、何番目にでも挿入できる汎用的なコードにしてください。
質問者は、なぜ返信してこないのだろうか?
理解できないのなら、そう言ってくれれば、詳しく説明するのに。

汎用的なコードです。

コード:

#include <stdlib.h>
 
#define N 10
 
struct cell {
    int data;
    struct cell *next;
};
typedef struct cell Cell;
 
void print(const Cell *p)
{
    for (; p; p = p->next)
        printf(" %d", p->data);
    putchar('\n');
}

Cell *insert(Cell *head, int data, int n)
{
    Cell *p = (Cell *)malloc(sizeof(Cell));
    p->data = data;
    if (--n <= 0 || head == NULL) {
        p->next = head;
        return p;
    }
    Cell *q = head;
    for (int i = 1; i < n && q->next; i++)
        q = q->next;
    p->next = q->next;
    q->next = p;
    return head;
}

int main(void)
{
    Cell *head = NULL;
    for (int i = 0; i < N; i++) {
        Cell *p = (Cell *)malloc(sizeof(Cell));
        p->data = 10 + (int)(rand()*(50-10+1.0)/(1.0+RAND_MAX));
        p->next = head;
        head = p;
    }
    print(head);
    int n, data = 100;
    while (printf("n: "), scanf("%d", &n) == 1) {
        head = insert(head, data++, n);
        print(head);
    }
    return 0;
}
実行結果

コード:

 40 43 46 24 29 33 43 17 33 10
n: 3
 40 43 100 46 24 29 33 43 17 33 10
n: 11
 40 43 100 46 24 29 33 43 17 33 101 10
n: 13
 40 43 100 46 24 29 33 43 17 33 101 10 102
n: 1
 103 40 43 100 46 24 29 33 43 17 33 101 10 102
n: 0
 104 103 40 43 100 46 24 29 33 43 17 33 101 10 102
n: .