2016-10-28 1 views
0

私はC言語を使い始めています。これらのリンクリスト構造をメイン関数に宣言して、リンクされたリストの要素から値をどのように出力するかを示します。ヘルプCのリンクリスト構造の要素にアクセスしようとしていて、構造体要素の関数を呼び出す

#include <stdio.h> 
#include <stdlib.h> 

void main() { 

} 

struct element { 
    struct element * next; 
    int data; 
}; 
struct linked_list { 
    struct element * head; 
}; 

void append_int(struct linked_list * list, int val) { 
    struct element * elem = malloc(sizeof(struct element)); 
    elem->data = val; 
    elem->next = NULL; // Really important to explicitly set this to null. Malloc does not zero memory 
    if (list->head == NULL) { 
    // Empty list, we need to append to head 
    list->head = elem; 
    } else { 
    // List has some elements, find the end and append to that 
    struct element * tail = list->head; 
    while (tail->next != NULL) { 
     tail = tail->next; 
    } 
    tail->next = elem; 
    } 
} 

void deletehead(struct linked_list * list) { 
    while(list->head) { 
    struct element * temp_head = list->head->next; 
    free(list->head); 
    list->head = temp_head; 
    } 
} 

void inserthead(struct linked_list * list, int val) { 
    struct element * new_node = malloc(sizeof(struct element)); 
    new_node->data = val; 
    struct element * temp_head2 = list->head; 
    list->head = new_node; 
    new_node->next = temp_head2; 
} 
+0

私は理解していません - あなたは構造のためにちょうど良い定義された機能の束を持っています - あなたの質問は何ですか? – Hogan

+0

コードはあなたのものですか?あなたはどこかでそれを見つけましたか?ポインタの概念とその使い方を理解していますか?あなたはポインタのために使用される演算子を知っていますか?あなたが持っているコードが何であるか理解していますか? –

+0

あなたはあなたが得る暗黙の宣言の警告を抑制するために、 'main'の前のどこかに関数宣言を含める必要があります – yano

答えて

0

ため

おかげで、あなたは最初に、「リンク」、オブジェクト指向プログラミングのように、あなたの「オブジェクト」である最初の要素へのポインタを保持する構造体linked_listを作成することができます。

また、必要に応じて機能を宣言することを忘れないでください!その上で関数を呼び出すために

struct linked_list* list = malloc(sizeof(linked_list)); 

inserthead(list, 5); 

あなたはOOPの背景から来ている場合は、すべての機能は静的であり、あなたが渡すことを考えることができるリンクリストを作成する

"list.insert()"のように呼び出す関数へのポインタ。

+0

私はまだこのコンパイラの問題を受けています{error: 'linked_list'は宣言されていません(この関数では最初に使用します) struct linked_list * list = malloc sizeof(linked_list)); ^ list.c:5:44:注意:宣言されていない各識別子は、表示される関数ごとに1回しか報告されません} – Fatboyover

+0

メインを他の関数の下に移動するか、または次のように宣言します void inserthead(struct linked_list *、int ); – Gmodjackass

+0

うわー、私は馬鹿だったよ、助けてくれてありがとう – Fatboyover

関連する問題