#ifndef _LINK_NODE_ #define _LINKE_NODE_ typedef struct Node { struct Node* pNext; void* pData; } NodeStruct, *pNodeStruct; typedef struct SingleLinkedList { pNodeStruct pHead; pNodeStruct pTail; } SingleLinkedListStruct, *pSingleLinkedListStruct; void init(pSingleLinkedListStruct*); void destory(pSingleLinkedListStruct*); void display(pSingleLinkedListStruct); void insertFront(pSingleLinkedListStruct*,void*); void insertTail(pSingleLinkedListStruct*,void*); void deleteNode(pSingleLinkedListStruct*,void*,int (*compare)(void*,void*)); int cmp(void* a,void* b) { int* pa=(int*)a; int* pb=(int*)b; if((*pa)==(*pb)) { return 1; }else return 0; } #endif
使用的是指向指针的指针,用来传递绝对地址;
#include <stdio.h> #include <malloc.h> #include "link.h" int main() { int a=90,b=80,c=20,d=2,e=2; pSingleLinkedListStruct pt=(pSingleLinkedListStruct)malloc(sizeof(SingleLinkedListStruct)); init(&pt); insertFront(&pt,&a); insertFront(&pt,&b); insertFront(&pt,&c); insertTail(&pt,&d); printf("------删除前--------\n"); display(pt); deleteNode(&pt,&e,cmp); //deleteNode(&pt,&c,cmp); printf("------删除后--------\n"); display(pt); return 0; } //-------------------------------- void init(pSingleLinkedListStruct* ps) { (*ps)->pHead=NULL; (*ps)->pTail=NULL; } void display(pSingleLinkedListStruct p) { pNodeStruct currentNode=p->pHead; while(currentNode) { printf("%d\n",*(int*)(currentNode->pData)); currentNode=currentNode->pNext; } } void insertFront(pSingleLinkedListStruct* p,void* data) { pNodeStruct currentNode=(pNodeStruct)malloc(sizeof(NodeStruct)); currentNode->pData=data; if((*p)->pHead==NULL) { currentNode->pNext=NULL; (*p)->pHead=currentNode; (*p)->pTail=currentNode; } else { currentNode->pNext=(*p)->pHead; (*p)->pHead=currentNode; } } void insertTail(pSingleLinkedListStruct* p,void* data) { pNodeStruct currentNode=(pNodeStruct)malloc(sizeof(NodeStruct)); currentNode->pData=data; if((*p)->pTail==NULL) { currentNode->pNext=NULL; (*p)->pHead=currentNode; (*p)->pTail=currentNode; } else { currentNode->pNext=NULL; (*p)->pTail->pNext=currentNode; (*p)->pTail=currentNode; } } void deleteNode(pSingleLinkedListStruct* p,void* data,int (*compare)(void*,void*)) { pNodeStruct cp=(*p)->pHead; pNodeStruct pre; while(cp) { if(compare(cp->pData,data)) { if(cp==(*p)->pHead) { (*p)->pHead=(*p)->pHead->pNext; return; } else { pre->pNext=cp->pNext; return; } } pre=cp; cp=cp->pNext; } }