内功修繕のデータ構造---チェーン表
前の配列に続き、このページでは主にチェーンを学習し、所与の位置の値を作成、遍歴、検索、挿入を実現しました.他の操作は書きません.基本的に似ています.コードを見て、詳しい注釈があります.
- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
- /*
- *
- *
- */
- typedef struct Node
- {
- int data;//
- struct Node * pNext;//
- }NODE,*PNODE;
-
-
- /**
- *
- * @return PNODE
- *
- */
- PNODE create(){
- int length;//
- printf(" length = ");
- scanf("%d",&length);
- //
- PNODE pHead = (PNODE)malloc(sizeof(NODE));
- if(NULL == pHead){
- printf(" ");
- exit(-1);
- }
- //
- PNODE pTail = pHead;//
- pTail->pNext = NULL;
- //
- int data;
- for(int i=1;i<=length;i++){
- // length
- PNODE pNode = (PNODE)malloc(sizeof(NODE));
- if(NULL == pNode){
- printf(" %d ",i);
- exit(-1);
- }
- printf(" %d :",i);
- scanf("%d",&data);
- pNode->data = data;
- pNode->pNext = NULL;
- pTail->pNext = pNode;// ,
- pTail = pNode;//
- }
- return pHead;
- }
-
-
- /**
- *
- * @param PNODE pHead
- */
- void traverse(PNODE pHead){
- if(NULL == pHead->pNext){
- printf(" ");
- exit(-1);
- }
- PNODE cNode = pHead->pNext;//
- int i = 1;//
- while(NULL != cNode){//
- printf(" %d :%d
",i,cNode->data);
- cNode = cNode->pNext;//
- i ++;
- }
- return;
- }
-
- /**
- *
- * @param PNODE pHead
- * @param int pos
- * @return int
- */
- int get(PNODE pHead,int pos){
- if(NULL == pHead->pNext){
- printf(" ");
- exit(-1);
- }
- PNODE cNode = pHead->pNext;//
- int i = 1;//
- while(NULL != cNode && i < pos){// pos
- cNode = cNode->pNext;
- i++;
- }
- if(NULL == cNode || i > pos){
- printf(" %d ",pos);
- exit(-1);
- }
- return cNode->data;
- }
-
- /**
- *
- * @param PNODE pHead
- * @param int pos
- * @param PNODE pNode
- */
- void insert(PNODE pHead,int pos,PNODE pNode){
- PNODE cNode = pHead->pNext;//
- int i = 1;//
- while(NULL != cNode && i < pos){// pos
- cNode = cNode->pNext;
- i++;
- }
- if(NULL == cNode || i > pos){
- printf(" %d
",pos);
- exit(-1);
- }
- if(NULL == cNode->pNext){// pos ,
- cNode->pNext = pNode;
- return;
- }
- pNode->pNext = cNode->pNext;//
- cNode->pNext = pNode;
- return;
- }
-
- void main(){
- PNODE pHead = NULL;//
- pHead = create();//
- traverse(pHead);//
- int data = get(pHead,2);// 2
- printf(" %d
",data);
- //
- NODE node;
- node.data = 100;
- node.pNext = NULL;
- insert(pHead,2,&node);
- traverse(pHead);
- }