Introducci贸n

1

驴Ya tomaste el Curso Avanzado de Algoritmos: Patrones de Arrays y Strings?

Lista Enlazada

2

Estructura de datos: Lista Enlazada

3

Programando listas enlazadas con Java

4

C贸mo Invertir una Lista Enlazada

5

Odd Even Linked List: an谩lisis del problema

6

Soluci贸n de Odd Even Linked List

7

Playground: Odd Even Liked List

8

Programando Odd Even Linked List con C++

9

Linked List Cycle: an谩lisis del problema

10

Soluci贸n de Linked List Cycle

11

Playground: Linked List Cycle

12

Programando Linked List Cycle con Python

13

Palindrome Linked List: an谩lisis del problema

14

Soluci贸n de Palindrome Linked List

15

Playground: Palindrome Linked List

16

Programando Palindrome Linked List con Java

17

Reorder List: an谩lisis del problema

18

Soluci贸n de Reorder List

19

Programando Reorder List con JavaScript

20

Playground: Reorder List Without Repeated Values

21

Reto: LRU Cach茅

22

Ejercicios recomendados de Lista Enlazada

23

Ejercicios resueltos de Lista Enlazada

Pilas y colas

24

Estructura de datos: Pilas y Colas

25

Par茅ntesis V谩lido: an谩lisis del problema

26

Soluci贸n de Par茅ntesis V谩lido

27

Playground: Par茅ntesis V谩lido

28

Programando Par茅ntesis V谩lido con C++

29

Ejercicios recomendados de Pilas

Colas de prioridad

30

Estructura de datos: Colas de Prioridad

31

K Closest Points to Origin: an谩lisis del problema

32

Soluci贸n de K Closest Points to Origin

33

Playground: K Closest Points to Origin

34

Programando K Closest Points to Origin con Python

35

Reorganize String: an谩lisis del problema

36

Soluci贸n de Reorganize String

37

Playground: Reorganize String

38

Programando Reorganize String con Python

39

Ejercicios recomendados de Colas de prioridad

40

Ejercicios resueltos de Colas de prioridad

Pr贸ximos pasos

41

Toma el Curso Avanzado de Algoritmos: Grafos y 脕rboles

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
10 Hrs
51 Min
32 Seg

C贸mo Invertir una Lista Enlazada

4/41
Resources

Contributions 7

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

La soluci贸n de la profe en Java, reverseLinkedList m茅todo que va en la clase ListaEnlazada realizada en la secci贸n previa, Java no permite la asignaci贸n paralela como en Python, por lo cual se usa la variable temp:

    public void reverseLinkedList() { 
        Nodo anterior = null;
        Nodo temp = null;
        Nodo cabezaInicial = this.cabeza;
        Nodo colaInicial = this.cola;
        
        while (this.cabeza != null) {
            temp = this.cabeza.siguiente; // Guardamos el Nodo cabeza.siguiente 
            this.cabeza.siguiente = anterior;	
            
            if ((this.cabeza.equals(colaInicial))) {
                /*
                 * Cuando llegamos al 煤tlimo Nodo de la lista, que ahora es cabeza,
                 * al Nodo cola le asignamos el Nodo cabeza inicial, es decir
                 * al Nodo cola le asignamos el Nodo con el cual se inici贸 el recorrido del while.
                 */
                this.cola = cabezaInicial;
                break;
            }
            
            anterior = this.cabeza;
            this.cabeza = temp;
        } 
    }

Cuando llegamos al 煤ltimo Nodo de la lista, se rompe el while antes de anterior = this.cabeza; this.cabeza = temp;, para que Nodo cabeza no apunte a null y para no hacer una asignaci贸n dem谩s a Nodo anterior.

Code to Reverse a LinkedList by C .\n ```js #include<stdio.h> #include <stdlib.h> int p = 0; //Definition for a linked list node here ..... struct node { int data; struct node *next; }; struct node *head = NULL; void addFirst(int val) { //Write your code here.... struct node *newNode = malloc(sizeof( struct node)); newNode->data = val; newNode->next = head; head = newNode; } void deleteNode(struct node **head, int key) { //Write your code here.... struct node *temp; if ( (*head)->data == key ) { temp = *head; *head = (*head)->next; free(temp); } else { struct node *current = *head; while ( current->next != NULL ) { if ( current->next->data == key ) { temp = current->next; current->next = current->next->next; free(temp); break; } else { current = current->next; } } } } //Don't change the below code void addLast(struct node **head, int val) { struct node *newNode = malloc(sizeof(struct node)); newNode->data = val; newNode->next = NULL; if(*head == NULL) *head = newNode; else { struct node *lastNode = *head; while(lastNode->next != NULL) { lastNode = lastNode->next; } lastNode->next = newNode; } } void printList(struct node *head) { struct node *temp = head; while(temp != NULL) { printf("%d ", temp->data); temp = temp->next; } } void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } //Function to Reverse a LinkedList from last element to head .... void reverse(struct node *head) { struct node *current = head ; struct node *prev = NULL ; struct node *n3xt = NULL ; while ( current != NULL ) { n3xt = current->next ; current->next = prev ; prev = current ; current = n3xt ; } head = prev ; } struct node* reverseSubList(struct node *head, int start, int end) { if ( start == end ) return head ; struct node *current = head; struct node *prev = NULL ; int i = 0; for ( i = 1 ; current != NULL && i < start ; i ++ ) { prev = current ; current = current->next ; } struct node *firstPartLastNode = prev; struct node *secondPartLastNode = current ; struct node *next ; for ( i = 1 ; current != NULL && i <= end - start + 1 ; i ++ ) { next = current->next; current->next = prev; prev = current; current = next; } if ( firstPartLastNode != NULL ) firstPartLastNode->next = prev ; else head = prev ; secondPartLastNode->next = current ; } int main ( void ) { struct node *head = NULL; addLast(&head,10); addLast(&head,20); addLast(&head,30); addLast(&head,40); addLast(&head,50); addLast(&head,60); addLast(&head,70); addLast(&head,80); addLast(&head,90); int key; scanf("%d",&key); deleteNode(&head, key); printList(head); reverse(head) ; printf("++++++++++++++000\n") ; printList( head ) ; printf("\n"); return 0 ; } ``` \#include\<stdio.h> \#include \<stdlib.h> int p = 0; //Definition for a linked list node here ..... struct node { int data; struct node \*next; }; struct node \*head = NULL; void addFirst(int val) { //Write your code here.... struct node \*newNode = malloc(sizeof( struct node)); newNode->data = val; newNode->next = head; head = newNode; } void deleteNode(struct node \*\*head, int key) { //Write your code here.... struct node \*temp; if ( (\*head)->data == key ) { temp = \*head; \*head = (\*head)->next; free(temp); } else { struct node \*current = \*head; while ( current->next != NULL ) { if ( current->next->data == key ) { temp = current->next; current->next = current->next->next; free(temp); break; } else { current = current->next; } } } } //Don't change the below code void addLast(struct node \*\*head, int val) { struct node \*newNode = malloc(sizeof(struct node)); newNode->data = val; newNode->next = NULL; if(\*head == NULL) \*head = newNode; else { struct node \*lastNode = \*head; while(lastNode->next != NULL) { lastNode = lastNode->next; } lastNode->next = newNode; } } void printList(struct node \*head) { struct node \*temp = head; while(temp != NULL) { printf("%d ", temp->data); temp = temp->next; } } void swap(int \*x, int \*y) { int temp = \*x; \*x = \*y; \*y = temp; } //Function to Reverse a LinkedList from last element to head .... void reverse(struct node \*head) { struct node \*current = head ; struct node \*prev = NULL ; struct node \*n3xt = NULL ; while ( current != NULL ) { n3xt = current->next ; current->next = prev ; prev = current ; current = n3xt ; } head = prev ; } struct node\* reverseSubList(struct node \*head, int start, int end) { if ( start == end ) return head ; struct node \*current = head; struct node \*prev = NULL ; int i = 0; for ( i = 1 ; current != NULL && i < start ; i ++ ) { prev = current ; current = current->next ; } struct node \*firstPartLastNode = prev; struct node \*secondPartLastNode = current ; struct node \*next ; for ( i = 1 ; current != NULL && i <= end - start + 1 ; i ++ ) { next = current->next; current->next = prev; prev = current; current = next; } if ( firstPartLastNode != NULL ) firstPartLastNode->next = prev ; else head = prev ; secondPartLastNode->next = current ; } int main ( void ) { struct node \*head = NULL; addLast(\&head,10); addLast(\&head,20); addLast(\&head,30); addLast(\&head,40); addLast(\&head,50); addLast(\&head,60); addLast(\&head,70); addLast(\&head,80); addLast(\&head,90); int key; scanf("%d",\&key); deleteNode(\&head, key); printList(head); reverse(head) ; printf("++++++++++++++000\n") ; printList( head ) ; printf("\n"); return 0 ; }
Codigo en TS: ```js function reverseList(head: ListNode | null): ListNode | null { let [p1, p2] = [head, null]; while (p1 != null) { p2 = new ListNode(p1.val, p2); p1 = p1.next; } return p2; }; ```function reverseList(head: ListNode | null): ListNode | null { let \[p1, p2] = \[head, null]; while (p1 != null) { p2 = new ListNode(p1.val, p2); p1 = p1.next; } return p2;};
```python class Node: def __init__(self, data): self.data = data self.next = None self.prev = None def __str__(self): return str(self.data) class Lista: def __init__(self): self.head, self.tail= None, None def __len__(self): length = 0 current = self.head while current: length += 1 current = current.next return length def append(self, data): new_node = Node(data) if self.head is None: self.head = new_node else: self.tail.next = new_node # Update the next pointer of the current tail node self.tail = new_node # Update the tail attribute to point to the new node return f'{data} has been added' def __str__(self): result = [] current = self.head while current: result.append(str(current)) current = current.next return ' -> '.join(result) + f', tail => {self.tail}' # Add tail information to the string representation def reverse(self): current = self.head previous = None while current != None: current.next, previous, current = previous, current, current.next self.head = previous return previous # Example usage: my_list = Lista() my_list.append(1) my_list.append(2) my_list.append(3) my_list.append(4) my_list.append(30) print(my_list) my_list.reverse() print(my_list) ```output 聽1 -> 2 -> 3 -> 4 -> 30, tail => 30 30 -> 4 -> 3 -> 2 -> 1, tail => 30
```python class Node: def __init__(self, data): self.data = data self.next = None self.prev = None def __str__(self): return str(self.data) class Lista: def __init__(self): self.head, self.tail= None, None def __len__(self): length = 0 current = self.head while current: length += 1 current = current.next return length def append(self, data): new_node = Node(data) if self.head is None: self.head = new_node else: self.tail.next = new_node # Update the next pointer of the current tail node self.tail = new_node # Update the tail attribute to point to the new node return f'{data} has been added' def __str__(self): result = [] current = self.head while current: result.append(str(current)) current = current.next return ' -> '.join(result) + f', tail => {self.tail}' # Add tail information to the string representation def reverse(self): current = self.head previous = None while current != None: current.next, previous, current = previous, current, current.next self.head = previous return previous # Example usage: my_list = Lista() my_list.append(1) my_list.append(2) my_list.append(3) my_list.append(4) my_list.append(30) print(my_list) my_list.reverse() print(my_list) ```class Node:聽 聽 def \_\_init\_\_(self, data):聽 聽 聽 聽 self.data = data聽 聽 聽 聽 self.next = None聽 聽 聽 聽 self.prev = None 聽 聽 def \_\_str\_\_(self):聽 聽 聽 聽 return str(self.data) class Lista: 聽 聽 def \_\_init\_\_(self):聽 聽 聽 聽 self.head, self.tail= None, None 聽 聽 def \_\_len\_\_(self):聽 聽 聽 聽 length = 0聽 聽 聽 聽 current = self.head聽 聽 聽 聽 while current:聽 聽 聽 聽 聽 聽 length += 1 聽 聽 聽 聽 聽 聽 current = current.next聽 聽 聽 聽 return length聽 聽 聽 聽 def append(self, data):聽 聽 聽 聽 new\_node = Node(data)聽 聽 聽 聽 if self.head is None:聽 聽 聽 聽 聽 聽 self.head = new\_node聽 聽 聽 聽 else:聽 聽 聽 聽 聽 聽 self.tail.next = new\_node 聽# Update the next pointer of the current tail node聽 聽 聽 聽 self.tail = new\_node 聽# Update the tail attribute to point to the new node聽 聽 聽 聽 return f'{data} has been added'聽 聽 聽 聽 def \_\_str\_\_(self):聽 聽 聽 聽 result = \[]聽 聽 聽 聽 current = self.head聽 聽 聽 聽 while current:聽 聽 聽 聽 聽 聽 result.append(str(current))聽 聽 聽 聽 聽 聽 current = current.next 聽 聽 聽 聽 return ' -> '.join(result) + f', tail => {self.tail}' 聽# Add tail information to the string representation聽 聽 聽 聽 def reverse(self):聽 聽 聽 聽 current = self.head聽 聽 聽 聽 previous = None聽 聽 聽 聽 while current != None:聽 聽 聽 聽 聽 聽 current.next, previous, current = previous, current, current.next聽 聽 聽 聽 self.head = previous聽 聽 聽 聽 return previous聽 聽 # Example usage:my\_list = Lista()my\_list.append(1)my\_list.append(2) my\_list.append(3)my\_list.append(4) my\_list.append(30)print(my\_list) my\_list.reverse()print(my\_list)

Hice la prueba con el codigo de la profe, y solo devolvia el primer nodo, toca quitarle el return y agregarle el cambio de cabeza con la cola:
self.head, self.tail = self.tail, self.head
.
comparto c贸digo con pruebas


.
Pruebas:

Otra soluci贸n:
Con Java, m茅todo dentro de la clase ListaEnlazada.

Mover el nodo cabeza y colocarlo entre el nodo cola y lo que apuntaba el nodo cola (esto se almacena en la aux para no perder esa parte de la lista). El nodo cola siempre ser谩 el mismo durante toda el recorrido del while hasta que 茅ste se convierta en actual y sea el primero de la lista y se lo asignemos a la cabeza.

Ej.: 1 -> 2 -> 3 -> 4

  1. Primera iteraci贸n: Movemos el 1 entre 4 y el null
    2 -> 3 -> 4 -> 1

  2. Segunda iteraci贸n. Movemos el 2 entre el 4 y el 1
    3 -> 4 -> 2 -> 1

  3. Tercera iteraci贸n: Movemos el 3 entre el 4 y el 2
    4 -> 3 -> 2 ->1

Como actual = 4 y es igual al Nodo colaInicial rompemos el ciclo y nuestra lista estar谩 reversada.

    public void reversarListaEnlazada() {
        
        Nodo colaInicial = this.cola;          //Guardamos el Nodo cola inicial
        Nodo cabezaInicial = this.cabeza;      //Guardamos el Nodo cabeza inicial
        Nodo actual = this.cabeza;
        Nodo aux = null;
        
        while (actual.siguiente != null) {
            if (actual.equals(colaInicial)) {    
                /*
                 * Si el nodo actual es igual al Nodo colaInicial,
                 * cambiamos por primera vez el puntero del nodo cola,
                 * y se lo asignamos al Nodo cabezaInicial.
                 */
                this.cola = cabezaInicial;
                break;
            } 
            actual = actual.siguiente;
            aux = this.cola.siguiente;
            this.cola.siguiente = this.cabeza;
            this.cabeza.siguiente = aux;
            this.cabeza = actual;
        }
    }