struct ListNode { int m_nValue; ListNode* m_pNext; }; //增加节点 /*第一个参数是一个指向指针的指针。当我们往一个空链表中插入一个节点时,新插入的节点 就是链表的头指针。由于此时会改动头指针,因此必须把pHead参数设为指向指针的指针*/ void addToTail(ListNode** pHead, int value) { ListNode* pNew = new ListNode(); pNew->m_pNext = NULL; pNew->m_nValue = value; if(*pHead == NULL) { *pHead = pNew; } else { ListNode* pNode = *pHead; //用临时节点来遍历链表以找出最后一个末尾基点 while(pNode->m_pNext) pNode = pNode->m_pNext; pNode->m_pNext = pNew; } } void removeNode(ListNode** pHead, int value) { if(*pHead == NULL || pHead == NULL) return; ListNode* pToBeDelete = NULL; //要被删除的节点放入pToBeDelete if((*pHead)->m_nValue == value) //如果是头结点要被删除 { pToBeDelete = *pHead; *pHead = (*pHead)->m_pNext; //改变头结点 } else { ListNode* pNode = *pHead; while(pNode->m_pNext != NULL && pNode->m_pNext->m_nValue != value) { pNode = pNode->m_pNext; //寻找被删除节点的上一个节点 } //找到节点 if(pNode->m_pNext != NULL && pNode->m_pNext->m_nValue != value == value) { pToBeDelete = pNode->m_pNext; pNode->m_pNext = pNode->m_pNext->m_pNext; //调整节点 } } if(pToBeDelete != NULL) { delete pToBeDelete; //删除节点 } }
链表节点的增加和删除
时间: 2024-10-16 03:36:28