题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
思路一:将链表中的连接指针反转过来,改变链表的方向就可以从头到尾输出了。不足:这样做会改变原来链表的结构。
思路二:遍历链表,遍历顺序是从头到尾而输出顺序却是从尾到头。也就是说第一个遍历到的结点最后一个输出,可以用栈实现。每当遍历到一个结点的时候,将该结点入栈。链表遍历结束后再从栈顶开始逐个输出结点的值。
思路三:用递归来实现。每访问到一个结点的时候,先递归输出它后面的结点在输出自己本身,这样链表的输出结果就反过来了。
思路二代码:
#include <iostream>
#include <stdlib.h>
#include <stack>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
ListNode *CreateList()
{
ListNode *pHead = NULL;
ListNode *pTail = NULL;
ListNode *pTemp = NULL;
int nNum;
cin >> nNum;
while(nNum != 0)
{
pTemp = (ListNode*)malloc(sizeof(ListNode));
pTemp->m_nKey = nNum;
pTemp->m_pNext = NULL;
if(pHead == NULL)
{
pHead = pTemp;
}
else
{
pTail->m_pNext = pTemp;
}
pTail = pTemp;
cin >> nNum;
}
return pHead;
}
void PrintListReversingly_Iteratively(ListNode* pHead)
{
stack<ListNode*> nodes;
ListNode* pNode = pHead;
while(pNode != NULL)
{
nodes.push(pNode);
pNode = pNode->m_pNext;
}
while(!nodes.empty())
{
pNode = nodes.top();
cout << pNode->m_nKey <<endl;
nodes.pop();
}
}
void Print(ListNode *pHead)
{
if(pHead == NULL) return ;
while(pHead)
{
cout << pHead->m_nKey << endl;
pHead = pHead->m_pNext;
}
}
int main()
{
ListNode* pHead = NULL;
pHead = CreateList();
Print(pHead);
PrintListReversingly_Iteratively(pHead);
return 0;
}
思路三代码:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
ListNode *CreateList()
{
ListNode *pHead = NULL;
ListNode *pTail = NULL;
ListNode *pTemp = NULL;
int nNum;
cin >> nNum;
while(nNum != 0)
{
pTemp = (ListNode*)malloc(sizeof(ListNode));
pTemp->m_nKey = nNum;
pTemp->m_pNext = NULL;
if(pHead == NULL)
{
pHead = pTemp;
}
else
{
pTail->m_pNext = pTemp;
}
pTail = pTemp;
cin >> nNum;
}
return pHead;
}
void PrintListReversingly_Iteratively(ListNode* pHead)
{
if(pHead != NULL)
{
if(pHead->m_pNext != NULL)
{
PrintListReversingly_Iteratively(pHead->m_pNext);
}
cout << pHead->m_nKey << endl;
}
}
void Print(ListNode *pHead)
{
if(pHead == NULL) return ;
while(pHead)
{
cout << pHead->m_nKey << endl;
pHead = pHead->m_pNext;
}
}
int main()
{
ListNode* pHead = NULL;
pHead = CreateList();
Print(pHead);
PrintListReversingly_Iteratively(pHead);
return 0;
}