题目:输入一个链表头结点,从尾到头反过来输出每个结点的值。
链表结点定义如下:
struct ListNode{ int m_nKey; ListNode* m_pNext;};
答:1、可以先把链表逆置,然后再输出,具体参考
这里我们使用另一种更为简单的方法:递归
#include "stdafx.h"#include#include using namespace std;struct ListNode{ int m_nKey; ListNode* m_pNext;};//构造链表void CreateList(ListNode *&pHead){ fstream fin("list.txt"); ListNode *pNode = NULL; ListNode *pTmp = NULL; int data; fin>>data; while (data) { pNode = new ListNode; pNode->m_nKey = data; pNode->m_pNext = NULL; if (NULL == pHead) { pHead = pNode; pTmp = pNode; } else { pTmp->m_pNext = pNode; pTmp = pNode; } fin>>data; }}//从头到尾输出链表void PrintList(ListNode *pHead){ if (NULL == pHead) { return; } ListNode *pNode = pHead; while (NULL != pNode) { cout< m_nKey<<" "; pNode = pNode->m_pNext; } cout< m_pNext); cout< m_nKey<<" "; }}int _tmain(int argc, _TCHAR* argv[]){ ListNode *pHead = NULL; CreateList(pHead); cout<<"从头到尾输出:"; PrintList(pHead); cout<<"从尾到头输出:"; PrintTailToHeadList(pHead); cout<
运行界面如下:
建造链表的list.txt文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 0