在完成第五题之前我想先复习一下链表的基本操作如下:
/**************************
struct ListNode
{
int Value;
ListNode* pNext;
}
***************************/
// 链表尾插法
// 注意头指针pHead的定义
// 判断链表是否为空
void AddToTail(ListNode ** pHead, int value)
{
ListNode* pNew = new ListNode();
pNew->Value = value;
pNew->pNext = NULL;
if(*pHead == NULL)
{
*pHead = pNew;
}
else
{
ListNode* pNode = *pHead;
while(pNode->pNext != NULL)
{
pNode = pNode->pNext;
}
pNode->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)->pNext;
}
else
{
ListNode* pNode = *pHead;
while(pNode->pNext != NULL
&& pNode->pNext->Value != value)
pNode = pNode->pNext;
if(pNode->pNext != NULL
&& pNode->pNext->Value == value)
{
pToBeDeleted = pNode->pNext;
pNode->pNext = pNode->pNext->pNext;
}
}
if(pToBeDeleted != NULL)
{
delete pToBeDeleted;
pToBeDeleted = NULL;
}
}
解题思路:本题只是让从尾到头打印一遍链表,并没有让改变输入的数据,所以用栈或递归比较好
//利用栈来实现
void PrintListReversingly_Iteratively(ListNode* pHead)
{
stack<ListNode *> nodes;
ListNode* pNode = pHead;
while(pNode != NULL)
{
nodes.push(pNode);
pNode = pNode->pNext;
}
while(!nodes.empty())
{
pNode = nodes.top();
printf("%d\t", pNode->Value);
nodes.pop();
}
}
//利用递归实现,递归本质上是一个栈结构
void PrintListReversingly_Recursively(ListNode* pHead)
{
if(pHead != NULL)
{
if(pHead->pNext != NULL)
{
PrintListReversingly_Recursively(pHead->pNext);
}
printf("%d\t", pHead->Value);
}
}