话不多说上代码
头文件 list.h:
#ifndef LIST_H #define LIST_H #include<stdio.h> #include<malloc.h> typedef struct Node *PNode; struct Node{ int elem; PNode next; }; int isEmpty(PNode p){ if(p->elem!=1) return 1; return 0; } int initNode(PNode &p){ p = (PNode)malloc(sizeof(Node)); p->next=NULL; p->elem=1; } int append(PNode &p,int elem){ PNode pp; initNode(pp); pp->next=p->next; pp->elem=elem; p->next=pp; } int delElem(PNode p,int id){ int i; for(i=1;p;i++){ if(i==id){ PNode pp=p->next; p->next=pp->next; free(pp); } p=p->next; } if(i<id) return 0; return 1; } int insertElem(PNode p,int id,int elem){ int i; for(i=1;p;i++){ if(i==id){ PNode pp; initNode(pp); pp->elem=elem; pp->next=p->next; p->next=pp; } p=p->next; } if(i<id) return 0; return 1; } int freeAllNode(PNode p){ while(p){ PNode temp=p; p=p->next; free(temp); } } int getlen(PNode p){ if(isEmpty(p)){ return 0; }else{ int len=0; while(p->next){ p=p->next; ++len; } return len; } } int locate(PNode p,int id){ for(int i=0;p;i++){ if(i==id){ return p->elem; } p=p->next; } printf("locate error\n"); return 0; } int readAll(PNode p){ if(!isEmpty(p)){ while(p->next){ p=p->next; printf("%d\n",p->elem); } }else{ printf("this list is EMPTY,if you want to use this list please INIT it first\n"); } } int union2list(PNode p1,PNode p2){ while(p1->next){ p1=p1->next; } p1->next=p2->next; free(p2); } #endifdemo : #include "list.h" #include<stdio.h> int main(){ PNode p; initNode(p); printf("append 1,2,3,4\n"); append(p,4); append(p,3); append(p,2); append(p,1); readAll(p); printf("delete id=3\n"); delElem(p,3); readAll(p); printf("the lenght of tne list\n"); printf("%d\n",getlen(p)); printf("create a list include (5,6,7,8)\n"); PNode pp; initNode(pp); append(pp,8); append(pp,7); append(pp,6); append(pp,5); readAll(pp); printf("mix list p and list pp\n"); union2list(p,pp); readAll(p); printf("get the value where id = 5\n"); printf("%d\n",locate(p,5)); printf("thank for use this .h :)"); return 0; } 本人还是c新手 若有不对的地方希望大家指正!!!