從尾到頭列印鏈表

來源:互聯網
上載者:User

標籤:鏈表   遞迴   

題目:輸入一個鏈表的頭結點,從尾到頭反過來列印出每個結點的值。(不能改變鏈表的結構)

struct ListNode

{

   int    m_nKey;

  ListNode*  m_pNext;

};

       本題中遍曆的順序是從頭到尾的順序,但是輸出卻是從尾到頭。所以該題符號棧的“後進先出”的特點。

因此可以用棧來實現這種順序。每經過一個結點的時候,把該結點放到棧中,當遍曆完整個鏈表後,再從棧頂開始逐個輸出結點的值。

void PrintListReversingly_Iteratively(ListNode* pHead)
{
std::stack<ListNode*>  nodes;
ListNode* pNode = pHead;
while (pNode! = NULL)
{
nodes.push(pNode);
pNode = pNode->m_pNext;
}
while (!nodes.empty())
{
pNode = nodes.top();
printf("%d\t", pNode->m_nValue);
nodes.pop();
}
}

解法二

     因為遞迴本質上就是一個棧結構,於是很自然地又想到了用遞迴來實現。要實現反過來輸出鏈表,我們每訪問到一個結點的時候,先遞迴輸出它後面的結點,再輸出該結點自身,這樣的鏈表的輸出結果就反過來了。

void PrintListReversingly_Recursively(ListNode* pHead)
{
if (pHead != NULL)
{
if (pHead->m_pNext != NULL)
{
PrintListReversingly_Recursively(pHead->m_pNext);
}
printf("%d\t", pHead->m_nValue);
}
}

    



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

從尾到頭列印鏈表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.