1 #include <iostream> 2 3 using namespace std; 4 5 struct Node{ 6 int data; 7 Node *next; 8 }; 9 10 Node* InitNodeList(){ 11 Node *node=0;//定义一个空指针 12 return node; 13 } 14 15 Node* addNode(Node *nodeList,Node *node) 16 { 17 if(nodeList == 0) 18 { 19 nodeList=node; 20 }else{ 21 nodeList->next = node; 22 } 23 node->next=0; 24 25 return nodeList; 26 } 27 28 Node* delNode(Node *nodeList,int data) 29 { 30 Node *p,*q; 31 p = q = nodeList; 32 33 if(nodeList == 0) 34 { 35 cout << "链表为空" << endl; 36 return nodeList; 37 } 38 if(nodeList->data == data) 39 { 40 nodeList=p->next; 41 delete p; 42 cout << "deleted" << endl; 43 } 44 else 45 { 46 while((p->data!=data)&&(p->next!=0)) 47 { 48 q=p; 49 p=p->next; 50 } 51 if((p->data)==data) 52 { 53 q->next=p->next; 54 delete p; 55 cout << "deleted" << endl; 56 }else 57 cout << "don't find the node:" << data << endl; 58 } 59 return nodeList; 60 } 61 62 void printNodeList(Node *nodeList) 63 { 64 Node *p=nodeList; 65 for(;p;) 66 { 67 cout << p->data << " "; 68 p=p->next; 69 } 70 cout << endl; 71 } 72 73 int main(void){ 74 Node *node=InitNodeList(); 75 76 Node *a=new Node; 77 a->data = 1; 78 Node *b = new Node; 79 b->data = 2; 80 81 node = addNode(node,a); 82 node = addNode(node,b); 83 84 printNodeList(node); 85 86 node = delNode(node,2); 87 printNodeList(node); 88 89 return 0; 90 }