C-鏈表增刪結點的問題(16)


Tip:下面代碼是通過結構體中某個值去實現的判斷是實現增刪的,具體依靠個人業務不同

void insert_element(struct Node *header,int keywordVal,int val){

struct Node *temp=header;
struct Node *mPrevious=NULL;
while (temp!=NULL)
{
if (temp->val==keywordVal)
{
//先連后斷
struct Node *pNewNode=(struct Node *)malloc(sizeof(struct Node));
pNewNode->val=val;
pNewNode->pNext=temp->pNext;
if (mPrevious!=NULL)
{
mPrevious->pNext=pNewNode;
pNewNode->pPrevious=mPrevious;
}
}
temp=temp->pNext;
mPrevious=temp;
}
}

struct Node * delete_element(struct Node *header,int keywordVal){
struct Node *mCurren=header;
struct Node *mPrivious=NULL;
struct Node *mNext=NULL;
//刪除第一個節點:只需要將head指向第二個節點
if (header->val==keywordVal)
{
return pHeader->pNext;
}

while (mCurren!=NULL)
{
//刪除最后一個節點,只需要將指向最后一個節點的指針(引用)指向NULL(null)
if (mCurren->pNext==NULL&&mCurren->val==keywordVal)
{
mPrivious->pNext=NULL;
}
//刪除中間節點,只要將需要將指向需要刪除節點的指針(引用)指向需要刪除節點的下一個節點
else if(mCurren->val==keywordVal)
{
mNext=mCurren->pNext;
mPrivious->pNext=mNext;
mNext->pPrevious=mPrivious;
}
mPrivious=mCurren;
mCurren=mCurren->pNext;
}
return header;
}


運行如下代碼:


結果:




注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com