链表操作程序
#include<iostream> using namespace std; struct listNode { int value; listNode* pNext; }; void AddToTail(listNode** pHead,int value) { listNode* newNode=new listNode(); newNode->pNext=NULL; newNode->value=value; if(*pHead==NULL) { *pHead=newNode; }else { listNode *pTemp=*pHead; while(pTemp->pNext!=NULL) pTemp=pTemp->pNext; pTemp->pNext=newNode; } } void printList(listNode** pHead) { if((pHead)==NULL) { cout<<"the list is empty"<<endl; }else { listNode* pTemp=*pHead; while(pTemp->pNext!=NULL) { cout<<pTemp->value<<endl; pTemp=pTemp->pNext; } cout<<pTemp->value<<endl; } }
void removeNode(listNode** pHead,int value) { if(pHead==NULL||(*pHead)==NULL) { return; } listNode *ToBeDelete=NULL; if((*pHead)->value==value) { ToBeDelete=*pHead; }else { listNode *pTemp=*pHead; while(pTemp->pNext!=NULL&&pTemp->pNext->value!=value) pTemp=pTemp->pNext; if(pTemp->pNext!=NULL&&pTemp->pNext->value) { ToBeDelete=pTemp->pNext; pTemp->pNext=pTemp->pNext->pNext; } } if(ToBeDelete!=NULL) { delete ToBeDelete; ToBeDelete=NULL; } } int main(void) { listNode *ls1=NULL; AddToTail(&ls1,1); AddToTail(&ls1,2); AddToTail(&ls1,3); AddToTail(&ls1,4); printList(&ls1); removeNode(&ls1,4); printList(&ls1); return 1; }