にリンクリストの先頭に要素を追加します。私は私のリンクリストの先頭に新しいリストを追加しようとしています、そしてそれは私が以下に定義の長さの関数から取得プリントアウトに基づいて動作していないです。は、私がリンクリストにスタンフォードCSエド・ライブラリのチュートリアルを以下のよC
#include <stdio.h>
#include <stdlib.h>
//build new struct for node
//node has value and points to next node
struct node{
int value;
struct node *next;
};
//declare a new struct node that contains 3 nodes (head, middle, tail)
struct node *Build123(){
struct node *head, *middle, *tail = NULL;
head = malloc(sizeof(struct node));
middle = malloc(sizeof(struct node));
tail = malloc(sizeof(struct node));
head->value = 3;
head->next = middle;
middle->value = 5;
middle->next = tail;
tail->value = 9;
tail->next = NULL;
return head;
};
//declare a function Length and variable counter to calculate size of list
int Length(struct node *head) {
int count = 0;
struct node *iterator = head;
while (iterator != NULL) {
count++;
iterator = iterator->next;
}
return count;
}
//declare function Push to add new lists that would be added to the front
void Push (struct node **headRef, int value){
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->value = value;
newNode->next = *headRef;
}
int main(){
//instantiate the 3 element linked list named beast
struct node *beast = Build123();
//add 2 elements to the front of the linked list via pass by reference
Push(&beast, 6);
Push(&beast, 12);
//calculate length of linked list after elements have been added
int len = Length(beast);
//print length of linked list to screen
printf("%d\n",len);
return 0;
}
私は5
を受け取ることを期待するとき、私は、3
を取得します。私が期待している値を得ることができないコードのエラーを見つけるのを助けてくれますか?私は何度も手を触れていたにもかかわらず、なぜそれを理解することができませんありがとうございました!
「あなたが設定されるでしょう」 - それが追加されている場所に依存します。 –
「追加」とは、「終わり」を意味していました。しかし、はい、明らかにそれは合理的な場所になければなりません。 –
"add"は "最後に"という意味ではありません。他の2つの答えは明示的です。 –