单链表的逆序输出
来源:互联网 发布:安卓版数据恢复软件 编辑:程序博客网 时间: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
- 单链表的逆序输出
- 单链表的逆序输出
- 单链表的逆序输出
- 单链表的逆序输出
- 单链表逆序或者逆序输出
- 单链表的动态建立和逆序输出
- 字符串的逆序输出
- 整数的逆序输出
- 数组的逆序输出
- 字符的逆序输出
- 逆序输出的数列
- 逆序的BSF输出
- 数组的逆序输出
- 字符串的逆序输出
- 数组的逆序输出
- 输出三位数的逆序
- 如何逆序输出单链表?
- 单链表逆序输出
- 函数的缺省参数
- c++中的string常用函数用法总结
- android使用kotlin开发基础(一)之 hello kotlin
- 杨老师:Visual C++ 中操纵 MS Word 123
- View的事件分发机制解析
- 单链表的逆序输出
- MQL指标:MACD
- IOS9 UIStackView简介
- 函数库【收集中】
- 面试如何谈自己做过的项目
- CF 120 D.Three Sons【细节题】
- linux inode 详解
- 分析Linux内核fork子进程的过程
- 电商平台学习笔记(八)——面向接口编程案例分析