私は新しい学習者で、リンクされたリストを作成しようとしています。私はそうすることができますが、ルートまたは最初のノードのポインターを保持しようとしているので、リンクされたリストを作成した後、リストを読み取ったり、パターン マッチングを実行したりできますが、正常に実行できません。ここで助けてもらえますか?
#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
int main(){
int d;
struct node *linked;
struct node *head;
linked = malloc (sizeof(struct node));
head = linked; <<<< As this is pointer, in while loop whenever malloc executes it changes the value of head as well.
printf ("Location of head %p \n", head->next);
d = 1;
while (d>0){
printf ("Enter the value of X: ");
scanf ("%d", &linked->x);
linked->next = malloc (sizeof(struct node));
printf ("Location of linked %p \n", linked->next);
printf ("Location of head %p \n", head->next);
printf ("To enter further value enter non zero: ");
scanf ("%d", &d);
if (d==0)
linked->next = NULL;
}
//linked->next = NULL;
printf("Value of Next is %p\n", linked->next);
printf ("Location of head %p \n", head->next);
}
出力:
MacBook-Air:cprog jimdev$ ./a.out
ヘッドの位置 0x7fff90ab952c <<<< この値は変更すべきではありませんが、ここでは後続の出力で変更します。
X: 0 の値を入力します。
リンクされた 0x7ff0624039c0 の場所
先頭の位置 0x7ff0624039c0 <<<< 以前とは異なる値
さらに値を入力するには、ゼロ以外を入力してください: 3
X: 3 の値を入力します。
リンクされた 0x7ff0624039d0 の場所
ヘッドの位置 0x7ff0624039d0 <<<< 以前とは異なる値
さらに値を入力するには、ゼロ以外を入力してください: 0
Next の値は 0x0 です
先頭の位置 0x0
リンクされたリスト要素のprintfも行うこの新しいものを試しました。改善点があれば教えてください。再帰がそれを達成するための迅速できちんとした方法であることは知っていますが、while ループで何かを試してみたかったのです。
含む
含む
構造体ノード {
int x;
struct node *next;
};
int メイン () {
int d, hold, i;
struct node *list;
struct node *head;
struct node *current;
list = (node *)malloc(sizeof(struct node));
head = list;
printf ("Location of list is %p \n", head);
d = 1;
ながら (d>0){
printf ("Enter the value of X: ");
scanf ("%d", &list->x);
printf ("Location of list is %p\n", list);
current = (node *)malloc (sizeof (struct node));
list->next = current;
list = current;
printf ("Location of head is %p\n", head);
printf ("Enter zero to terminate the loop: ");
scanf ("%d", &d);
}
list->next = NULL;
printf ("Value of last next is %d\n", list->next);
current = head;
i = 1;
while (current->next != 0){
printf ("Location of list is %p \n", current);
printf ("Value of linked list %d elements %d \n", i, current->x);
current = current->next;
i++;
}
scanf ("%d", &hold);
}