本文主要描述了链表相关的题目的解答方案
下面叙述了相关的链表单元定义的基本结构
如下写法方便于书写测试代码
struct ListNode //所有的链表都是由链表节点构成的,所以在这里 命名为ListNode
{
int m_nValue; //m 表示member n 表示整数
ListNode* m_pNext; //此处有cpp 格式特点
}; //注意在c++ 中 class 以及struct 都有分号
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);
下面是 初始化 链表的一些基本构成代码 ,复用性非常强可以作为以后笔试中的标准模板代码
#include "stdafx.h"
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
ListNode* CreateListNode(int value)
{
ListNode* pNode = new ListNode(); //创建节点首先需要 index 节点 ,所以需要 pNode
pNode->m_nValue = value;
pNode->m_pNext = NULL;
return pNode;
}
void ConnectListNodes(ListNode* pCurrent, ListNode* pNext) //连接两个节点 pCurrent pNext
{
if(pCurrent == NULL)
{
printf("Error to connect two nodes.\n");
exit(1);
}
pCurrent->m_pNext = pNext; //不需要判断pNext 是否合法 即使是NULL 也没有关系 ,null 是java 中的表示方法
}
void PrintListNode(ListNode* pNode) //打印链表节点 pNode 作为index 节点
{
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("PrintList starts.\n");
ListNode* pNode = pHead; // 需要定义指针pNode 元素
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) // pNew 是新增的节点 pNode 是节点 头结点定义为 指向指针的指针 ,是因为可能为空链表 ,NULL 赋值为 链 //表头 ,当函数结束之后 链表头还是为NULL
{
ListNode* pNew = new ListNode();
pNew->m_nValue = value;
pNew->m_pNext = NULL;
if(*pHead == NULL) //
{
*pHead = pNew;
}
else
{
ListNode* pNode = *pHead;
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)->m_nValue == value)
{
pToBeDeleted = *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)
{
pToBeDeleted = pNode->m_pNext;
pNode->m_pNext = pNode->m_pNext->m_pNext;
}
}
if(pToBeDeleted != NULL)
{
delete pToBeDeleted;
pToBeDeleted = NULL;
}
}