-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.h
118 lines (96 loc) · 1.99 KB
/
node.h
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
110
111
112
113
114
115
116
117
118
//
// node.h
// linkedList
//
// Created by Ian Petty on 10/19/16.
// Copyright © 2016 Ian Petty. All rights reserved.
//
#ifndef node_h
#define node_h
#include <stdio.h>
template <class T>
class Node
{
public:
T data;
Node * pNext;
Node() : pNext(NULL) {}
Node(T data) : data(data), pNext(NULL) {}
};
template <class T>
Node<T> * copy(Node<T>* rhs)
{
Node<T> * pFirst = new Node<T>;
Node<T> * pTemp = rhs;
Node<T> * pCurrent = pFirst;
pFirst->data = rhs->data;
while (pTemp->pNext)
{
pCurrent->pNext = new Node<T>;
pCurrent = pCurrent->pNext;
pTemp = pTemp->pNext;
pCurrent->data = pTemp->data;
}
return pFirst;
}
template <class T>
void insert (T data, Node<T> * & pNode, bool isHead = false)
{
if (pNode == NULL)
{
Node<T> * temp = new Node<T> (data);
pNode = temp;
}
else if (isHead == false)
{
Node<T> * pNew = new Node<T> (data);
pNew->pNext = pNode->pNext;
pNode->pNext = pNew;
}
else
{
Node<T> * pNew = new Node<T> (data);
pNew->pNext = pNode;
pNode = pNew;
}
}
template <class T>
Node<T> * find (Node<T> * pHead, const T & data)
{
Node<T> * pCurrent = pHead;
while(pCurrent)
{
if(pCurrent->data == data)
{
return pCurrent;
}
pCurrent = pCurrent->pNext;
}
pCurrent = NULL;
return pCurrent;
}
template <class T>
std::ostream & operator << (std::ostream & out, const Node<T> * pNode)
{
for(const Node<T> * p = pNode; p; p = p->pNext)
{
if (p->pNext != NULL)
out << p->data << ", ";
else
out << p->data;
}
return out;
}
template <class T>
void freeData(Node<T>* & pNode)
{
Node<T> * temp = pNode;
while (pNode != NULL)
{
temp = pNode->pNext;
delete pNode;
pNode = temp;
}
pNode = NULL;
}
#endif /* node_h */