// 面试题6:从尾到头打印链表
// 题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
思路:从尾到头打印链表,可以从头到尾遍历链表,利用栈先进后出的性质,实现这一题。
#include<iostream>
#include<stack>
#include<stdio.h>
using namespace std;
struct ListNode {
int m_value;
ListNode *m_next;
};
void PrintListReversingly_Iteratively(ListNode * phead)
{
std::stack<ListNode *> nodes;
ListNode *pNode = phead;
while (pNode != nullptr)
{
nodes.push(pNode);
pNode = pNode->m_next;
}
while (!nodes.empty())
{
pNode = nodes.top();
printf("%d ", pNode->m_value);
nodes.pop();
}
}
//递归实现
void PrintListReversingly_Iteratively(ListNode * phead)
{
if (phead != nullptr)
{
if (phead->m_next != nullptr)
{
PrintListReversingly_Iteratively(phead->m_next);
}
printf("%d ", phead->m_value);
}
}
// 面试题8:二叉树的下一个结点
// 题目:给定一棵二叉树和其中的一个结点,如何找出中序遍历顺序的下一个结点?
// 树中的结点除了有两个分别指向左右子结点的指针以外,还有一个指向父结点的指针。
思路:除去一直右子树,没有后一个节点的,其他两种情况,1.根节点右子树的第一个节点,该节点只要有左子
树,一直沿着左子树向左遍历,若给定节点在此范围,则通过这种方式查找到后,该节点的父节点即为下一个节
点。(即如果一个节点有右子树,那么该节点下一个节点为右子树的最左边的节点)2.若该节点没有右子树,则
沿着该节点的父节点的寻找,直至其中一个节点是他的父节点的左子节点,则该父节点是原始给定节点的下一个
节点。至于其中没有后一个节点的情况,代码中,在循环外和else if()循环中处理后,都指向nullptr。
#include<iostream>
#include<stdio.h>
using namespace std;
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
BinaryTreeNode *m_pParent;
};
BinaryTreeNode *GetNext(BinaryTreeNode *pNode)
{
if (pNode == nullptr)
return nullptr;
BinaryTreeNode *pNext = nullptr;
if (pNode->m_pRight != nullptr)
{
BinaryTreeNode *pRight = pNode->m_pRight;
while (pRight->m_pLeft != nullptr)
{
pRight = pRight->m_pLeft;
}
pNext = pRight;
}
else if (pNode->m_pParent != nullptr)
{
BinaryTreeNode * pCurrent = pNode;
while (pCurrent->m_pParent != nullptr && pCurrent->m_pParent->m_pRight == pCurrent)
{
pCurrent = pCurrent->m_pParent;
}
pNext = pCurrent->m_pParent;
}
return pNext;//若没有下一个节点,若没有进两个条件语句,返回初始的nullptr,若进入了第二个if循环,直接返回的 nullptr。不为空后,
//current变为根节点,parent为空,赋值给pNext的也为空。
}