閱讀183 返回首頁    go 技術社區[雲棲]


從尾到頭輸出鏈表


題目:輸入一個鏈表頭結點,從尾到頭反過來輸出每個結點的值。

鏈表結點定義如下:

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

答:1、可以先把鏈表逆置,然後再輸出,具體參考

      https://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;
}

最後更新:2017-04-03 15:21:46

  上一篇:go Spark連接Hadoop讀取HDFS問題小結
  下一篇:go uva 1378 - A Funny Stone Game sg函數