-
Notifications
You must be signed in to change notification settings - Fork 1
/
tailtohead.cpp
109 lines (86 loc) · 2.2 KB
/
tailtohead.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// {"category": "List", "notes": "Print a list from tail to head"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <memory>
#include <stack>
using namespace std;
//------------------------------------------------------------------------------
//
// Please implement a function to print a list from its tail to head.
//
//------------------------------------------------------------------------------
template<class Object>
class ListNode
{
public:
ListNode<Object>(const Object& object = Object());
void Add(const Object& object);
private:
Object m_object;
shared_ptr<ListNode<Object>> m_spNext;
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
public:
void ReversePrint();
};
template<class Object>
void ListNode<Object>::ReversePrint()
{
stack<shared_ptr<ListNode<Object>>> nodes;
shared_ptr<ListNode<Object>> spNext = m_spNext;
while (spNext != nullptr)
{
nodes.push(spNext);
spNext = spNext->m_spNext;
}
while (!nodes.empty())
{
cout << nodes.top()->m_object << " ";
nodes.pop();
}
cout << endl;
}
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
template<class Object>
ListNode<Object>::ListNode(const Object& object)
: m_object(object), m_spNext(nullptr)
{
}
template<class Object>
void ListNode<Object>::Add(const Object& object)
{
shared_ptr<ListNode<Object>> spNext = shared_ptr<ListNode<Object>>(
new ListNode<Object>(object));
if (nullptr == m_spNext)
{
m_spNext = spNext;
}
else
{
shared_ptr<ListNode<Object>> spLast = m_spNext;
while (spLast->m_spNext != nullptr)
{
spLast = spLast->m_spNext;
}
spLast->m_spNext = spNext;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
ListNode<int> listHead;
for (int i = 1; i <= 10; i++)
{
listHead.Add(i);
}
listHead.ReversePrint();
return 0;
}