list.h
//list.h
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);
list.cpp
//创建一个结点
ListNode* CreateListNode(int value)
{
ListNode* Node = new ListNode();
pNode->m_nValue = value;
pNode->m_pNext = NULL;
return pNode;
}
//连接两个结点
void ConnectListNode(ListNode* pCurrent, ListNode* pNext)
{
if(pCurrent == NULL)
{
printf("Error to connect two nodes\n");
exit(1);
}
pCurrent->m_pNext = pNext;
}
//打印结点值
void PrintListNode(ListNode* pNode)
{
if(pNode == NULL)
{
printf("The Node is NULL\n");
}
else
{
printf("The Key in node is %d.\n", pNode->m_nValue);
}
}
//打印链表
void PrintList(ListNode* pHead)
{
printf("\nPrintList starts.\n");
ListNode* pNode = *pHead;
while(pNode != NULL)
{
printf("%d\t", pNode->m_nValue);
pNode = pNode->m_pNext;
}
printf("\nPrintList ends.\n");
}
//删除链表
void DestroyList(ListNode* pHead)
{
ListNode* pNode = pHead;
while(pNode != NULL)
{
pHead = pHead->m_pNext
delete pNode;
pNode = pHead;
}
}
//单向链表末尾添加一个结点
void AddToTail(ListNode** pHead, int value)
{
ListNode* pNew = new ListNode();
pNew->m_nValue = value;
pNew->m_pNext = NULL;
//若是空链表
if(*pHead == NULL)
*pHead = pNew;
else
{
ListNode* pNode = *pHead;
//找到最后一个结点,此时pNode指向尾结点
while(pNode->m_pNext != NULL)
pNode = pNode->m_pNext;
pNode->m_pNext = pNew;
}
}
//在链表中找到第一个含有某值的结点并删除该结点
void RemoveNode(ListNode** pHead, int value)
{
//空链表
if(pHead == NULL || *pHead == NULL)
return;
ListNode* pToBeDeleted = NULL;
//如果要删除的结点为首结点
if((*pHead)->value == value)
{
pToBeDeleted = *pHead;
*pHead = (*pHead)->m_pNext;
}
else
{
ListNode* pNode = *pHead;
//退出while循环的条件是(1)到达尾结点
//(2) 找到与value匹配的结点
//pNode指向将被删结点的前一个结点
while(pNode->m_pNext != NULL && pNode->m_pNext->m_nValue != value)
pNode = pNode->m_pNext;
//注意if条件内容
if(pNode->m_pNext != NULL && pNode->m_pNext->m_nValue == value)
{
pToBeDeleted = pNode->m_pNext;
pNode->m_pNext = pNode->m_pNext->m_pNext;
}
//确定存在与valude值匹配的将要删除的结点
if(pToBeDeleted!= NULL)
{
delete pToBeDeleted;
pToBeDeleted = NULL;
}
}
}
网友评论