根据 位置 删除节点
#include<iostream>
struct ListNode{
int m_nValue;
ListNode* m_pNext;
};
ListNode* AddToTail(ListNode** pHead, int Value)
{
ListNode* pNew = new ListNode();
pNew->m_nValue = Value;
pNew->m_pNext = nullptr;
if(*pHead == NULL){
*pHead = pNew;}
else{
ListNode* pNode = *pHead;
while(pNode->m_pNext != nullptr)
pNode = pNode->m_pNext;
pNode->m_pNext = pNew;}
return *pHead;
}
void Delete(ListNode** pHead, int position)
{
if(pHead == nullptr || *pHead == nullptr)
return;
ListNode* pToBeDelete = *pHead;
if(position == 1)
*pHead = pToBeDelete->m_pNext;
else{
ListNode* pNode = *pHead;
for(int i=0;i<position-2;i++)
pNode = pNode->m_pNext;
pToBeDelete = pNode->m_pNext;
pNode->m_pNext = pToBeDelete->m_pNext;
}
if(pToBeDelete!=nullptr){
delete pToBeDelete;
pToBeDelete = nullptr;
}
}
void print(ListNode* pHead){
printf("LinkedList is:\n");
while(pHead!=nullptr)
{
printf("%d ", pHead->m_nValue);
pHead = pHead->m_pNext;
}
printf("\n");
}
int main(){
ListNode* pHead = nullptr;
pHead = AddToTail(&pHead, 1);
pHead = AddToTail(&pHead, 2);
pHead = AddToTail(&pHead, 3);
pHead = AddToTail(&pHead, 4);
Delete(&pHead, 1);
print(pHead);
}
运行结果:
根据 值 删除节点
#include<iostream>
struct ListNode{
int m_nValue;
ListNode* m_pNext;
};
ListNode* AddToTail(ListNode** pHead, int Value)
{
ListNode* pNew = new ListNode();
pNew->m_nValue = Value;
pNew->m_pNext = 0;
if(*pHead == 0){
*pHead = pNew;}
else{
ListNode* pNode = *pHead;
while(pNode->m_pNext != 0)
pNode = pNode->m_pNext;
pNode->m_pNext = pNew;}
return *pHead;
}
void Delete(ListNode** pHead, int value)
{
if(pHead == 0 || *pHead == 0)
return;
ListNode* pToBeDelete = *pHead;
if(pToBeDelete->m_nValue == value)
{
pToBeDelete = *pHead;
*pHead = pToBeDelete->m_pNext;
}
else
{
ListNode* pNode = *pHead;
while(pNode->m_pNext->m_nValue == value){
pNode = pNode->m_pNext;}
pToBeDelete = pNode->m_pNext;
pNode->m_pNext = pToBeDelete->m_pNext;
}
if(pToBeDelete!=0){
delete pToBeDelete;
pToBeDelete = 0;
}
}
void print(ListNode* pHead){
printf("LinkedList is:\n");
while(pHead!=0)
{
printf("%d ", pHead->m_nValue);
pHead = pHead->m_pNext;
}
printf("\n");
}
int main(){
ListNode* pHead = 0;
pHead = AddToTail(&pHead, 1);
pHead = AddToTail(&pHead, 2);
pHead = AddToTail(&pHead, 3);
pHead = AddToTail(&pHead, 4);
Delete(&pHead, 1);
print(pHead);
}
运行结果:
有问题,欢迎留言。
编程就是算法和数据结构,算法和数据结构是编程的灵魂。