/*单链表的顺序输出,即从头结点开始,一次后移,输出;单链表的逆序输出,可先将其结点从头结点开始一次入栈,再从栈顶开始,依次出栈即可*/
//先创建链表结点的结构体
链表结点.h
struct
ListNode
{
int
value;
ListNode *next;
};
#include <iostream>
#include <stack>
#include "链表结点.h"
using
namespace
std;
//创建链表
ListNode *creatList()
{
int
value=0;
ListNode* pHead=
new
ListNode();
ListNode* pNode=pHead;
while
((value+1) != 0)
{
cin>>value;
ListNode *pNew=
new
ListNode();
pNew->value=value;
pNew->next=NULL;
pNode->next=pNew;
pNode=pNew;
}
pHead=pHead->next;
return
pHead;
}
//逆序输出
void
printListreverse(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;
return
0;
}
|
单链表的逆序输出
最新推荐文章于 2023-05-21 13:26:57 发布