私は C プログラミングのスキルを向上させようとしているので、二重連結リストのプログラミングを試みることから始めました。
これが私がこれまでに思いついたものです。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
//forward definition
typedef struct Node node_t;
//Define the structures needed for double linked list
//Each node
typedef struct Node
{
int data;
node_t *next;
node_t *prev;
}node_t;
void initList(node_t** first , node_t** last)
{
//Allocate memory for the first and the last node
*first = (node_t*) malloc(sizeof(node_t));
*last = (node_t*) malloc(sizeof(node_t));
(*first)->data = 1;
(*last)->data = 2;
(*first)->prev = NULL;
(*last)->next = NULL;
(*first)->next = (*last)->prev;
return;
}
void destroyList(node_t** first)
{
node_t* temp;
temp = *first;
free((*first)->next);
free((*first));
temp = NULL;
return;
}
int main()
{
node_t *first =NULL, *last = NULL;
printf("Initalizing the List\n");
initList(&first,&last);
printf(" 1st element is %d\n",first->data);
printf(" 2nd element is %d\n",last->data);
printf("Destroying the List\n");
destroyList(&first) ;
return 0;
}
私は実際にオンラインでいくつかのコードを調べましたが、ほとんどの実装には
1) Node 用の 1 つの構造体と List 自体用の 1 つの構造体 (頭と尾を含む)。私の質問は、これは必須ですか? 1つの構造だけで実装できないのですか?
2)私の考えは、このファイルをライブラリとして作成し、アプリケーションから呼び出すことです。InitList
()、DestroyList()、AddNode、DeleteNode などのように。
そのため、INit と destroy に二重ポインタを使用しています。リストの破棄に問題があります。私はそれが間違っていることを知っています、私はそれを修正し続けます。
3) そのノードポインタを見つけました
temp = first
あるアドレスを指していました。私がtemp ++を行う場合。次のノードを指していないのはなぜですか?
4) リスト全体を削除するために、最初または最後のノード ポインタを渡すことができますよね?. (つまり、トラバースしてシーケンシャルに削除しますか?)
ありがとう!