题目:输入一个链表的头结点,从尾到头反过来输出每个结点的值。链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
分析:这是一道很有意思的面试题。该题以及它的变体经常出现在各大公司的面试、笔试题中。
看到这道题后,第一反应是从头到尾输出比较简单。于是很自然地想到把链表中链接结点的指针反转过来,改变链表的方向。然后就可以从头到尾输出了。反转链表的算法详见本人面试题精选系列的第19题,在此不再细述。但该方法需要额外的操作,应该还有更好的方法。
接下来的想法是从头到尾遍历链表,每经过一个结点的时候,把该结点放到一个栈中。当遍历完整个链表后,再从栈顶开始输出结点的值,此时输出的结点的顺序已经反转过来了。该方法需要维护一个额外的栈,实现起来比较麻烦。
既然想到了栈来实现这个函数,而递归本质上就是一个栈结构。于是很自然的又想到了用递归来实现。要实现反过来输出链表,我们每访问到一个结点的时候,先递归输出它后面的结点,再输出该结点自身,这样链表的输出结果就反过来了。
基于这样的思路,不难写出如下代码:
// ReverseLink.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
ListNode* link_create(int n)//创建n个节点的循环链表
{
//先创建第1个节点
ListNode *p,*q,*head;
int i ;
p = (ListNode *)malloc(sizeof(ListNode));
head = p;
p->m_nKey = 1;
for(i = 2;i<=n;i++)//再创建剩余节点
{
q = (ListNode *)malloc(sizeof(ListNode));
q->m_nKey = i;
p->m_pNext = q;
p = q;
}
p->m_pNext = NULL;//最后一个节点指向头部,形成循环链表
return head;
}
ListNode* ReverseIteratively(ListNode* pHead)//本身就把链表进行了翻转,按顺序打印就是翻转后链表的元素
{
ListNode* pReversedHead = NULL;
ListNode* pNode = pHead;
ListNode* pPrev = NULL;
while(pNode != NULL)
{
// get the next node, and save it at pNext
ListNode* pNext = pNode->m_pNext;
// if the next node is null, the currect is the end of original
// list, and it's the head of the reversed list
if(pNext == NULL)
pReversedHead = pNode;
// reverse the linkage between nodes
pNode->m_pNext = pPrev;
// move forward on the the list
pPrev = pNode;
pNode = pNext;
}
return pReversedHead;
}
//使用递归实现链表反向输出
void PrintListReversely(ListNode* pListHead)
{
if(pListHead != NULL)
{
// Print the next node first
if (pListHead->m_pNext != NULL)
{
PrintListReversely(pListHead->m_pNext);
}
// Print this node
printf("%d", pListHead->m_nKey);
}
}
void Printf_Link_Reverse(ListNode* phead)
{
if (phead!=NULL)
{
if (phead->m_pNext!=NULL)//先递归出后面的节点
{
Printf_Link_Reverse(phead->m_pNext);
}
cout<<phead->m_nKey;//打印出自身
}
}
int _tmain(int argc, _TCHAR* argv[])
{
ListNode* phead=link_create(8);
//phead=ReverseIteratively(phead);
Printf_Link_Reverse(phead);//使用递归实现链表的反向输出
system("pause");
return 0;
}