C++链表逆序打印节点

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值