-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathListLinked.h
129 lines (117 loc) · 2.23 KB
/
ListLinked.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
119
120
121
122
123
124
125
126
127
128
129
#include <ostream>
#include "List.h"
#include "Node.h"
template <typename T>
class ListLinked : public List<T> {
private:
Node<T>* first;
int n;
public:
ListLinked(){
first = nullptr;
n = 0;
}
~ListLinked(){
Node<T>* aux;
for(int i = 0; i < n; i++){
aux = first->next;
delete first;
first = aux;
}
n = 0;
}
T operator[](int pos){
Node<T>* aux = first;
if(pos >= 0 && pos <= n){
return get(pos);
}else{
throw std::out_of_range("Posición fuera del array.");
}
}
friend std::ostream& operator<<(std::ostream &out, const ListLinked<T> &list){
Node<T>* aux = list.first;
out << "List [";
for(int i = 0; i < list.n; i++){
out << " " << aux->data;
aux = aux->next;
}
out << " ]";
return out;
}
void insert(int pos, T e){
Node<T>* aux = first;
Node<T>* preaux = nullptr;
if(pos >= 0 && pos <= n){
if(!pos){
first = new Node<T>(e);
first->next = aux;
}else{
for(int i = 0; i < pos; i++){
preaux = aux;
aux = aux->next;
}
preaux->next = new Node<T>(e);
preaux = preaux->next;
preaux->next = aux;
}
n++;
}else{
throw std::out_of_range("Posición fuera del array.");
}
}
void append(T e){
insert(n, e);
}
void prepend(T e){
insert(0, e);
}
T remove(int pos){
Node<T>* aux = first;
Node<T>* preaux = nullptr;
if(pos >= 0 && pos < n){
if(!pos){
first = aux->next;
}else{
for(int i = 0; i < pos; i++){
preaux = aux;
aux = aux->next;
}
preaux->next = aux->next;
}
aux->next = nullptr;
n--;
return aux->data;
}else{
throw std::out_of_range("Posición fuera del array.");
}
}
T get(int pos){
Node<T>* aux = first;
if(pos >= 0 && pos < n){
for(int i = 0; i < pos; i++){
aux = aux->next;
}
return aux->data;
}else{
throw std::out_of_range("Posición fuera del array.");
}
}
int search(T e){
Node<T>* aux = first;
int pos = -1;
for(int i = 0; i < n; i++){
if(e == aux->data){
pos = i;
break;
}
aux = aux->next;
}
return pos;
}
bool empty(){
return n == 0;
}
int size(){
return n;
}
};