从尾到头打印链表
题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
解法1:利用栈实现
废话不多说,直接上代码:
void Solution::printListRevers(ListNode *pHead)
{
if(!pHead)
return;
std::stack<ListNode *> s_Nodes;
ListNode *pNode = pHead->pNext;
while(NULL != pNode)
{
s_Nodes.push(pNode);
pNode = pNode->pNext;
}
while (!s_Nodes.empty())
{
printf("%d ", s_Nodes.top()->data);
s_Nodes.pop();
}
return;
}
解法2:递归实现
需要注意,当链表非常长时,就会导致函数掉用的层级很深,有可能栈溢出;所以解法1较好。
void listNodeRecursion(ListNode *pHead)
{
if(pHead)
{
listNodeRecursion(pHead->pNext);
printf("%d ", pHead->data);
}
return;
}
void Solution::printListReversRecursion(ListNode *pHead)
{
if(!pHead)
return;
ListNode *pTmpHead = pHead->pNext;
listNodeRecursion(pTmpHead);
return;
}
完整代码
#include "string.h"
#include "stdio.h"
#include <stack>
#include <iostream>
using namespace std;
struct ListNode
{
int data;
ListNode *pNext;
};
class Solution
{
public:
Solution();
~Solution();
ListNode* InitList_head( int n);
ListNode* InitList_Tail( int n);
void printListRevers(ListNode *pHead);
void printListReversRecursion(ListNode *pHead);
};
Solution::Solution()
{}
Solution::~Solution()
{
}
ListNode* Solution::InitList_head(int n)
{
ListNode *pHead = (ListNode*)malloc(sizeof(ListNode));
pHead->pNext = NULL;
ListNode *pTmpHead = pHead;
for(int i=0;i<n;i++)
{
ListNode *pNewNode = (ListNode*)malloc(sizeof(ListNode));
pNewNode->data = i;
pNewNode->pNext = pTmpHead->pNext;
pTmpHead->pNext = pNewNode;
}
return pHead;
}
ListNode* Solution::InitList_Tail(int n)
{
ListNode *pHead = (ListNode*)malloc(sizeof(ListNode));
pHead->pNext = NULL;
ListNode *pTmpTail = pHead;
for(int i=0;i<n;i++)
{
ListNode *pNewNode = (ListNode*)malloc(sizeof(ListNode));
pNewNode->data = i;
pTmpTail->pNext = pNewNode;
pNewNode->pNext = NULL;
pTmpTail = pTmpTail->pNext;
}
return pHead;
}
void Solution::printListRevers(ListNode *pHead)
{
if(!pHead)
return;
std::stack<ListNode *> s_Nodes;
ListNode *pNode = pHead->pNext;
while(NULL != pNode)
{
s_Nodes.push(pNode);
pNode = pNode->pNext;
}
while (!s_Nodes.empty())
{
printf("%d ", s_Nodes.top()->data);
s_Nodes.pop();
}
return;
}
void listNodeRecursion(ListNode *pHead)
{
if(pHead)
{
listNodeRecursion(pHead->pNext);
printf("%d ", pHead->data);
}
return;
}
void Solution::printListReversRecursion(ListNode *pHead)
{
if(!pHead)
return;
ListNode *pTmpHead = pHead->pNext;
listNodeRecursion(pTmpHead);
return;
}
int main()
{
Solution oTest;
ListNode *pList = oTest.InitList_Tail(8);
oTest.printListRevers(pList);
printf("\n");
oTest.printListReversRecursion(pList);
std::cin.get();
return 0;
}