题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值。链表节点定义如下:
struct ListNode
{
int m_nkey;
ListNode* m_pNext;
};
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct ListNode
{
int m_nkey;
ListNode* m_pNext;
};
ListNode* CreateLinkedList(vector<int> values)
{
ListNode* head = nullptr;
ListNode* tail = nullptr;
for(int value : values)
{
ListNode* newNode = new ListNode;
newNode->m_nkey = value;
newNode->m_pNext = nullptr;
if (head == nullptr)
{
head = newNode;
tail = newNode;
}
else
{
tail->m_pNext = newNode;
tail = newNode;
}
}
return head;
}
void PrintList(ListNode* pHead)
{
std::stack<ListNode*> nodes;
ListNode* pNode = pHead;
while(pNode != nullptr)
{
nodes.push(pNode);
pNode = pNode -> m_pNext;
}
while(! nodes.empty())
{
pNode = nodes.top();
cout << pNode -> m_nkey <<" ";
nodes.pop();
}
}
int main()
{
std::vector<int> nodeValues;
nodeValues.push_back(1);
nodeValues.push_back(2);
nodeValues.push_back(3);
nodeValues.push_back(4);
nodeValues.push_back(5);
ListNode* head = CreateLinkedList(nodeValues);
PrintList(head);
return 0;
}
void PrintList(ListNode* pHead)
{
if(pHead != nullptr)
{
if(pHead->m_pNext != nullptr)
{
PrintList(pHead->m_pNext);
}
cout << pHead->m_nkey << " ";
}
}
解题思路:这道题主要是针对链表的简单操作,不是很难,两种方法:栈&递归。