• 从尾到头输出链表


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

    链表结点定义如下:

    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;
    }

    运行界面如下:

    建造链表的list.txt文件如下:

    1 2 3 4 5 6 7 8 9 10 11 12 0
  • 相关阅读:
    超大文件上传-如何上传文件-大文件上传
    局域网 前端大文件上传
    B/S 前端大文件上传
    PHP 前端大文件上传
    .NET 前端大文件上传
    C#.NET 前端大文件上传
    ASP.NET 前端大文件上传
    SpringBoot 前端大文件上传
    SpringMVC 前端大文件上传
    JAVA 前端大文件上传
  • 原文地址:https://www.cnblogs.com/venow/p/2657680.html
Copyright © 2020-2023  润新知