-
Notifications
You must be signed in to change notification settings - Fork 1
/
reverselist.cpp
88 lines (72 loc) · 1.89 KB
/
reverselist.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
// {"category": "List", "notes": "Reverse a linked list (recursive)"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <Windows.h>
using namespace std;
//------------------------------------------------------------------------------
//
// Reverse a linked-list.
//
//------------------------------------------------------------------------------
template<class Object>
class ListNode
{
public:
Object m_object;
ListNode<Object>* m_pNext;
ListNode(const Object& object, ListNode<Object>* pNext = nullptr)
: m_object(object), m_pNext(pNext) {}
};
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
template<class Object>
ListNode<Object>* reverse(ListNode<Object>* pNode)
{
if (nullptr == pNode)
{
return nullptr;
}
ListNode<Object>* pHead = pNode;
if (pNode->m_pNext != nullptr)
{
pHead = reverse(pNode->m_pNext);
pNode->m_pNext->m_pNext = pNode;
pNode->m_pNext = nullptr;
}
return pHead;
}
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
ListNode<int> node5(5);
ListNode<int> node4(4, &node5);
ListNode<int> node3(3, &node4);
ListNode<int> node2(2, &node3);
ListNode<int> node1(1, &node2);
ListNode<int>* tests[] =
{
&node5,
&node1,
nullptr,
};
for (int i = 0; i < ARRAYSIZE(tests); i++)
{
ListNode<int>* pNode = reverse(tests[i]);
while (pNode != nullptr)
{
cout << pNode->m_object << " ";
pNode = pNode->m_pNext;
}
cout << endl;
}
return 0;
}