问题:输入一个链表的头结点,从尾到头反过来打印每个节点的值。
输入:一个链表的头结点。
输出:打印从尾到头的节点的值。
思路:借用栈这一数据结构,遍历链表,将值存放在栈中。然后出栈,进行打印。
代码:
本地调试代码(迭代法)
#include <iostream>
//#include ".\Utilities\List.h"
#include <stack>
using namespace std;
struct ListNode
{
int m_nValue;
ListNode* m_pNext;
};
ListNode* CreateListNode(int value)
{
ListNode* pNode = new ListNode();
pNode->m_nValue = value;
pNode->m_pNext = nullptr;
return pNode;
}
void ConnectListNodes(ListNode* pCurrent, ListNode* pNext)
{
if(pCurrent == nullptr)
{
printf("Error to connect two nodes.\n");
exit(1);
}
pCurrent->m_pNext = pNext;
}
void DestroyList(ListNode* pHead)
{
ListNode* pNode = pHead;
while(pNode != nullptr)
{
pHead = pHead->m_pNext;
delete pNode;
pNode = pHead;
}
}
void PrintListReversingly_Iteratively(ListNode* pHead)
{
stack<int> nodes;
ListNode* pNode= pHead;
int nValue;
if(pNode!=nullptr)
{
nodes.push(pNode->m_nValue);
while(pNode->m_pNext!=nullptr)
{
pNode = pNode->m_pNext;
nodes.push(pNode->m_nValue);
}
}
while(!nodes.empty()) {
nValue = nodes.top();
cout<<nValue<<endl;
nodes.pop();
}
}
int main()
{
ListNode* pNode1 = CreateListNode(1);
ListNode* pNode2 = CreateListNode(2);
ListNode* pNode3 = CreateListNode(3);
ListNode* pNode4 = CreateListNode(4);
ListNode* pNode5 = CreateListNode(5);
ConnectListNodes(pNode1, pNode2);
ConnectListNodes(pNode2, pNode3);
ConnectListNodes(pNode3, pNode4);
ConnectListNodes(pNode4, pNode5);
PrintListReversingly_Iteratively(pNode1);
DestroyList(pNode1);
return 0;
}
递归法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> res;
vector<int> reversePrint(ListNode* head) {
if(head!=NULL)
{
reversePrint(head->next);
res.push_back(head->val);
}
return res;
}
};
牛客网代码:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
//#include <stack>
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> arrayList;
//stack<int> values; 借用stack,超出内存限制,故用vector的reverse方法代替
//int value;
if(head!=nullptr)
{
arrayList.push_back(head->val);
while(head->next!=nullptr)
{
head=head->next;
arrayList.push_back(head->val);
}
}
//while(!values.empty())
//{
// value = values.top();
// arrayList.push_back(value);
//}
reverse(arrayList.begin(), arrayList.end());
return arrayList;
}
};
复杂度分析:时间复杂度为O(n),空间复杂度为O(n)。