Created
April 23, 2022 06:21
-
-
Save wmoralesdev/0aa0207a9830a89dbd9a0fe4c50c35b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "../ds/ds.hpp" | |
using namespace std; | |
node* getInterval(node* list, int n, int d); | |
void push(node** list, node* n); | |
int main(void) { | |
node* list = new node(1); | |
list->next = new node(2); | |
list->next->next = new node(3); | |
list->next->next->next = new node(4); | |
list->next->next->next->next = new node(5); | |
list->next->next->next->next->next = new node(6); | |
node* interval = getInterval(list, 3, 2); | |
cout << interval; | |
return 0; | |
} | |
node* getInterval(node* list, int n, int d) { | |
// n es la posicion, d es la variacion, ejemplo n = 5, d = 2 ... [3, 8] | |
// Convertir lista a un arreglo | |
// 1. obtener tamaño | |
int size = 0; | |
node* aux = list; | |
while(aux){ | |
aux = aux->next; | |
size++; | |
} | |
// 2. Crear un arreglo de tipo nodo | |
node* listAsArray = new node[size]; | |
// 3. llenar arreglo | |
// Cada posicion del arreglo es de tipo nodo y no nodo*, la lista es diferente | |
// cada elemento de la lista es un nodo* entonces debe haber una conversion al colocar | |
// dichos elementos | |
int pos = 0; | |
for(node* auxArray = list; auxArray != NULL; auxArray = auxArray->next, pos++) { | |
// Guardar el nodo dentro del arreglo | |
listAsArray[pos] = (*auxArray); | |
} | |
// 4. Crear una nueva lista para los elementos del intervalo | |
node* interval = NULL; | |
// 5. Obtener por posicion los nodos | |
for(int i = n - d; i <= n + d; i++) { | |
push(&interval, &listAsArray[i]); | |
} | |
// 6. Retornar intervalo | |
return interval; | |
} | |
void push(node** list, node* n) { | |
// Caso especial del ejercicio, debe isolarse el n a insertar | |
n->next = NULL; | |
if(!*list) { | |
*list = n; | |
} | |
else { | |
node* aux = *list; | |
while(aux->next) | |
aux = aux->next; | |
aux->next = n; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment