struct ListNode{ int m_nValue; ListNode* m_pNext; } ListNode* CreateListNode(int value); void ConnectListNodes(ListNode* pCurrent, ListNode* pNext); void PrintListNode(ListNode* pNode); void PrintList(ListNode* pHead); void DestroyList(ListNode* pHead); void AddToTail(ListNode** pHead, int value); void RemoveNode(ListNode** pHead, int value);
//创建链表 ListNode* CreateListNode(int value){ ListNode* pNode = new ListNode(); pNode->m_nValue = value; pNode->m_pNext = nullptr; return pNode; } //添加元素 void AddToTail(ListNode** pHead,int value){ ListNode* pNew = new ListNode(); pNew->value = value; pNew->next = nullptr; if(*pHead == nullptr) *pHead = pNew; else{ ListNode* pNode = new ListNode(); pNode = *pHead; while(*pHead != nullptr) pHead = pHead->m_pNext; pNode->m_pNext = pNew; } } //删除元素 void RemoveNode(ListNode** pHead,int value){ if(pHead == nullptr || *pHead == nullptr) return; ListNode* pToBeDeleted = nullptr; if((*pHead)->m_nValue == value){ pToBeDeleted = *pHead; *pHead = (*pHead)->m_pNext; } else{ ListNode* pNode = *pHead; while(pNode->m_pNext != nullptr && pNode->m_pNext->m_nValue != value) pNode = pNode->m_pNext; if(pNode->m_pNext != nullptr && pNode->m_pNext->m_nValue == value){ pToBeDelted = pNode->m_pNext; pNode->m_pNext = pNode->m_pNext->m_pNext; } } if(pToBeDeleted != nullptr){ delete pToBeDeleted; pToBeDeleted = nullptr; } } //销毁链表 void DestroyList(ListNode* pHead){ ListNode* pNode = pHead; while(pNode != nullptr){ pHead = pHead->m_pNext; delete[] pNode; pNode = pHead; } } //打印链表 void PrintList(ListNode* pHead){ printf("PringList starts. "); ListNOde* pNode = pHead; whiel(pNode != nullptr){ printf("%d ",pNode->m_nValue); pNode = pNode->m_pNext; } printf("PrintLisr end. "); } //打印节点 void PrintListNode(ListNode* pNode){ if(pNode == nullptr){ printf("The node is nullptr. "); } else{ printf("The key node is %d. ",pNode->m_nValue); } } //连接两个节点 void ConnectListNodes(ListNode* pCurrent,ListNode* pNext){ if(pCurrent == nullptr){ printf("Error to connect two nodes. "); exit(1); } pCurrent->m_pNext = pNext; }