單鏈表的逆序輸出

/*單鏈表的順序輸出,即從頭結點開始,一次後移,輸出;單鏈表的逆序輸出,可先將其結點從頭結點開始一次入棧,再從棧頂開始,依次出棧即可*/
 
 
//先創建鏈表結點的結構體
鏈表結點.h
structListNode
{
    intvalue;
    ListNode *next;
};
  
#include <iostream>
#include <stack>
#include "鏈表結點.h"
usingnamespace std;
  
//創建鏈表
ListNode *creatList()
{
    intvalue=0;
    ListNode* pHead=newListNode();
    ListNode* pNode=pHead;
    while((value+1) != 0)
    {
        cin>>value;
        ListNode *pNew=newListNode();
        pNew->value=value;
        pNew->next=NULL;
  
        pNode->next=pNew;
        pNode=pNew;
  
    }
    pHead=pHead->next;
  
    returnpHead;
}
  
//逆序輸出
voidprintListreverse(ListNode *pHead)
{
    stack<ListNode*> nodes;
      
    ListNode* pNode=pHead;
    while(pNode != NULL)
    {
        nodes.push(pNode);
        pNode=pNode->next;
    }
  
    while(!nodes.empty())
    {
        pNode=nodes.top();
        cout <<pNode->value <<" ";
        nodes.pop();
    }
}
  
  
int main()
{
    ListNode*phead=creatList();
    ListNode*pnode=phead;
  
    cout <<"順序輸出鏈表:"<<endl;
    while(pnode!=NULL)
    {
        cout <<pnode->value <<" ";
        pnode=pnode->next;
    }      //此時pnode指向最後的節點
  
    cout <<"\n逆序輸出鏈表:"<<endl;
    printListreverse(phead);  //必須要保證phead是鏈表的第一個節點,因此要聲明兩個指針,同時指向鏈表的第一個節點
    cout <<endl;
    return0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章