#include<iostream.h>
#include <stdio.h>
#include <stack>
//链表逆向输出
struct ListNode
{
int m_nValue;
ListNode * m_pNext;
};
ListNode * CreateLink(int a[],int k)
{
ListNode * Head=NULL,*q=NULL;
for(int i=0;i<k;i++)
{
ListNode * pNew=new ListNode();
pNew->m_nValue=a[i];
pNew->m_pNext=NULL;
if(Head==NULL)
{
Head=pNew;
q=pNew;
}
else
{
q->m_pNext=pNew;
q=q->m_pNext;
}
}
return Head;
}
//从头到尾打印列表
void printLink(ListNode * pHead)
{
ListNode *p=pHead;
while(p)
{
cout<<p->m_nValue<<" ";
p=p->m_pNext;
}
cout<<endl;
}
//从尾到头打印链表
//知识点1. 使用栈
void PrintListReversesingly_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();
cout<<pNode->m_nValue<<" ";
nodes.pop();
}
}
//递归从尾到头打印链表
void PrintListReversesingly_Recursively(ListNode * pHead)
{
if(pHead != NULL)
{
if (pHead->m_pNext != NULL)
{
PrintListReversesingly_Recursively(pHead->m_pNext);
}
printf("%d\t", pHead->m_nValue);
}
}
//====测试用例===
void test1()
{
int a[]={1,2,3};
ListNode * Head=CreateLink(a,3);
printLink(Head);
PrintListReversesingly_Iteratively(Head);
PrintListReversesingly_Recursively(Head);
}
void test2()
{
PrintListReversesingly_Iteratively(NULL);
PrintListReversesingly_Recursively(NULL);
}
void test3()
{
int a[]={1};
ListNode * Head=CreateLink(a,1);
printLink(Head);
PrintListReversesingly_Iteratively(Head);
PrintListReversesingly_Recursively(Head);
}
void main()
{
cout<<"test1()"<<endl;
test1();
cout<<endl;
cout<<"test2"<<endl;
test2();
cout<<endl;
cout<<"test3"<<endl;
test3();
}
【剑指offer】链表相关-逆向输出
最新推荐文章于 2022-05-07 23:15:48 发布