单链表的逆序输出

来源:互联网 发布:安卓版数据恢复软件 编辑:程序博客网 时间:2024/06/05 00:41

从尾到头打印单链表.
          这里只是简单写了一个可以实现正常功能的单链表,(未实现析构函数)由于单链表只能一般从前向后遍历,这样按题目的要求先访问者后输出,正好与栈的的功能相同,用栈能解决的问题都可以用递归的方法实现。这里我用了递归的方法
# include <iostream>
# include <cassert>
using namespace std;
struct ListNode
{
           size_t _data;
           ListNode *_next;
          ListNode()
                   :_data(0)
                   , _next( NULL)
          {}
};
class List
{
private :
           ListNode *head;
           ListNode *tail;
public :
          List()
                   :head( new ListNode )
                   , tail(head)
          {}
           bool Insert(size_t data)
          {
                   tail->_data = data;
                   tail->_next = new ListNode ;
                   tail = tail->_next;
                    if (tail != NULL )
                   {
                              return true ;
                   }
                    else
                   {
                              return false ;
                   }
          }
           void PrintHeadtoTail()
          {
                    assert(head);
                    ListNode *phead = head;
                    while (phead->_next != NULL)
                   {
                             cout << phead->_data << " " ;
                             phead = phead->_next;
                   }
                   cout << endl;
          }
           void PrintTailtoHead()
          {
                    assert(head);
                    ListNode *phead = head;
                   _PrintTailtoHead(phead);
                   cout << endl;

          }
protected :
           void _PrintTailtoHead(ListNode* phead)
          {
                    if (phead ->_next==NULL)
                   {
                              return;
                   }
                    else
                   {
                             _PrintTailtoHead( phead->_next);
                   }
                   cout << phead->_data << " ";
          }

};
int main()
{
           List L;
          L.Insert(1);
          L.Insert(2);
          L.Insert(3);
          L.Insert(4);
          L.Insert(5);
          L.Insert(6);
          L.Insert(7);
          L.Insert(8);
          L.Insert(9);
          L.PrintHeadtoTail();
          L.PrintTailtoHead();
           return 0;

}








0 0
原创粉丝点击