#include <iostream>
#include <stack>
using namespace std;
template<typename Type>
struct Node
{
Type data;
Node *next;
Node(Type d = Type()):data(d),next(NULL){}
};
template<typename Type>
class List
{
public:
List()
{
head = NULL;
}
void Insert(Type a[],int n)
{
for(int i=0;i<n;i++)
{
_Insert(head,a[i]);
}
}
void Printf()//顺序打印.
{
Node<Type> *p = head;
while(p!=NULL)
{
cout<<p->data<<"\t";
p = p->next;
}
cout<<endl;
}
void Printf_A()//递归逆序打印节点.
{
_Printf_A(head);
}
void Printf_B()
{
_Printf_B(head);//用栈实现逆序打印节点。
}
private:
void _Printf_B(Node<Type> *t)
{
Node<Type> *p = t;
stack<Node<Type> *> st;
while(p!=NULL)
{
st.push(p);
p = p->next;
}
while(st.empty()!=true)
{
p = st.top();
st.pop();
cout<<p->data<<"\t";
}
cout<<endl;
}
bool _Printf_A(Node<Type> *t)
{
if(t!=NULL)
{
_Printf_A(t->next);
cout<<t->data<<"\t";
}
}
bool _Insert(Node<Type> *t,Type val)
{
Node<Type> *p = t;
Node<Type> *s = new Node<Type>(val);
if(t==NULL)
{
head = s;
}
else
{
while(p->next!=NULL)
p=p->next;
p->next = s;
}
}
private:
Node<Type> *head;
};
int main()
{
int a[]={1,2,3,4,5,6,7,8};
List<int> list;
list.Insert(a,8);
// list.Printf_A();
//list.Printf();
list.Printf_B();
return 0;
}
时间: 2024-10-05 05:09:21