从尾到头输出链表


题目:输入一个链表头结点,从尾到头反过来输出每个结点的值。

链表结点定义如下:

struct ListNode
{
    int m_nKey;
    ListNode* m_pNext;
};

答:1、可以先把链表逆置,然后再输出,具体参考

      http://www.cnblogs.com/venow/archive/2012/08/26/2657559.html

     这里我们使用另一种更为简单的方法:递归


#include "stdafx.h"
#include <iostream>
#include <fstream>

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<<pNode->m_nKey<<"  ";
        pNode = pNode->m_pNext;
    }
    cout<<endl;
}

//从尾到头输出链表
void PrintTailToHeadList(ListNode *pHead)
{
    if (NULL != pHead)
    {
        PrintTailToHeadList(pHead->m_pNext);
        cout<<pHead->m_nKey<<"  ";
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    ListNode *pHead = NULL;
    CreateList(pHead);
    cout<<"从头到尾输出:";
    PrintList(pHead);
    cout<<"从尾到头输出:";
    PrintTailToHeadList(pHead);
    cout<<endl;
    return 0;
}
上一篇:安装gr_ieee802.11


下一篇:用ps CS5扣人物发丝图片教程