// testPPointer.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdlib.h>
typedef struct tagNode
{
struct tagNode* m_next;
int m_nVal;
}Node, *PNode;
// 通过二级指针方式删除节点
void DelNode_Val2(PNode* ppHead, int nVal);
void DelNode_Val2(PNode* ppHead, int nVal)
{
for (PNode* ppCurr = ppHead; *ppCurr != NULL;)
{
PNode pEntry = *ppCurr;
if (pEntry->m_nVal == nVal)
{
*ppCurr = pEntry->m_next;
free(pEntry);
}
else
{
ppCurr = &pEntry->m_next;
}
}
}
void DelNode_Val(PNode* ppHead, int nVal);
void DelNode_Val(PNode* ppHead, int nVal)
{
for (PNode pPre = NULL, pCurr = *ppHead; pCurr != NULL;)
{
PNode pNext = pCurr->m_next;
if (pCurr->m_nVal == nVal)
{
if (pPre == NULL)
{
*ppHead = pNext;
}
else
{
pPre->m_next = pNext;
}
free(pCurr);
}
else
{
pPre = pCurr;
}
pCurr = pNext;
}
}
void OutPut(PNode pHead);
void OutPut(PNode pHead)
{
for (PNode pCurr = pHead; pCurr != NULL; pCurr = pCurr->m_next)
{
printf("address:%d, val:%d\r\n", pCurr, pCurr->m_nVal);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
PNode pnode1 = (PNode)malloc(sizeof(Node));
pnode1->m_nVal = 1;
PNode pnode2 = (PNode)malloc(sizeof(Node));
pnode2->m_nVal = 2;
PNode pnode3 = (PNode)malloc(sizeof(Node));
pnode3->m_nVal = 3;
PNode pnode4 = (PNode)malloc(sizeof(Node));
pnode4->m_nVal = 4;
PNode pnode5 = (PNode)malloc(sizeof(Node));
pnode5->m_nVal = 5;
PNode pnode6 = (PNode)malloc(sizeof(Node));
pnode6->m_nVal = 6;
pnode1->m_next = pnode2;
pnode2->m_next = pnode3;
pnode3->m_next = pnode4;
pnode4->m_next = pnode5;
pnode5->m_next = pnode6;
pnode6->m_next = NULL;
PNode pHead = pnode1;
OutPut(pHead);
printf("*******************************\r\n");
DelNode_Val(&pHead, 3);
OutPut(pHead);
printf("*******************************\r\n");
DelNode_Val2(&pHead, 4);
OutPut(pHead);
return 0;
}
利用二级指针删除单向链表节点
最新推荐文章于 2024-04-19 16:09:27 发布