Cヘッドプラグ法とテールプラグ法を実現して双方向非循環チェーンテーブル(先頭ノードテールノード)を構築する
双方向チェーンテーブルにヘッドノードとテールノードがあれば、ヘッドプラグインとテールプラグインに便利です.これにより、末尾に要素を挿入してもチェーンテーブルを巡回する必要はありません.個人的には、このチェーンテーブルを使用して問題を処理することをお勧めします.コードのアップロード先https://github.com/chenyufeng1991/HeadInsertAndTailInsert_DoubleList_HeadList .
コアコードは次のとおりです.
テストコードは次のとおりです.
コアコードは次のとおりです.
// ( )
void HeadInsertCreateList(Node *pHead,Node *pTail){
Node *pInsert;
pInsert = (Node *)malloc(sizeof(Node));
memset(pInsert, 0, sizeof(Node));
pInsert->prior = NULL;
pInsert->next = NULL;
scanf("%d",&(pInsert->element));
while (pInsert->element > 0) {
pHead->next->prior = pInsert;
pInsert->next = pHead->next;
pInsert->prior = pHead;
pHead->next = pInsert;
pInsert = (Node *)malloc(sizeof(Node));
memset(pInsert, 0, sizeof(Node));
pInsert->prior = NULL;
pInsert->next = NULL;
scanf("%d",&(pInsert->element));
}
printf("%s ,
",__FUNCTION__);
}
// ( )
void TailInsertCreateList(Node *pHead,Node *pTail){
Node *pInsert;
pInsert = (Node *)malloc(sizeof(Node));
memset(pInsert, 0, sizeof(Node));
pInsert->prior = NULL;
pInsert->next = NULL;
scanf("%d",&(pInsert->element));
while (pInsert->element > 0) {
pTail->prior->next = pInsert;
pInsert->prior = pTail->prior;
pInsert->next = pTail;
pTail->prior = pInsert;
pInsert = (Node *)malloc(sizeof(Node));
memset(pInsert, 0, sizeof(Node));
pInsert->prior = NULL;
pInsert->next = NULL;
scanf("%d",&(pInsert->element));
}
printf("%s ,
",__FUNCTION__);
}
テストコードは次のとおりです.
int main(int argc, const char * argv[]) {
Node *pHead;//
Node *pTail;//
InitialList(&pHead, &pTail);
HeadInsertCreateList(pHead, pTail);
PrintList(pHead, pTail);
TailInsertCreateList(pHead, pTail);
PrintList(pHead, pTail);
return 0;
}