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:
publicvoidreverseLinkedList(){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.
Para que se pueda ver como queda:
@OverridepublicStringtoString(){String respuesta ="";if(cabeza ==null){//Si la lista es vacía respuesta ="ListaEnlazada{}";}elseif(this.cabeza!=null&&this.cabeza==this.cola){// Si la lista tiene solo 1 Nodo respuesta ="ListaEnlazada{cabeza:"+this.cabeza.valor+", cola: "+this.cola.valor+"}";}else{Nodo actual =this.cabeza;while(actual.siguiente!=null){ respuesta +="actual: "+ actual.valor+" -> "; actual = actual.siguiente;} respuesta +="actual: "+ actual.valor;}return respuesta;}
Aporte en C++:
#include<iostream>#include<vector>classNode{public: int val;Node*next;};Node*reverse_linked_list(Node*&list){if(!list)return nullptr;Node*prev = nullptr;Node*current = list;while(current){Node*tmp = current->next; current->next = prev; prev = current; current = tmp;}return prev;}int main(){std::vector<int> elems ={4,5,1,2,6,9,8,7};Node*list =newNode;Node*current = list; list->val = elems[0];for(int c=1;c<elems.size();c++){ current->next =newNode; current->next->val = elems[c]; current = current->next;} current->next = nullptr; current = list;while(current){std::cout << current->val << std::endl; current = current->next;}Node* reversed =reverse_linked_list(list); current = reversed;while(current){std::cout << current->val << std::endl; current = current->next;}return0;}
Code to Reverse a LinkedList by C .\n
#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;voidaddFirst(int val){//Write your code here.... struct node *newNode =malloc(sizeof( struct node)); newNode->data = val; newNode->next = head; head = newNode;}voiddeleteNode(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 codevoidaddLast(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;}}voidprintList(struct node *head){ struct node *temp = head;while(temp !=NULL){printf("%d ", temp->data); temp = temp->next;}}voidswap(int *x, int *y){ int temp =*x;*x =*y;*y = temp;}//Function to Reverse a LinkedList from last element to head ....voidreverse(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");return0;}
classNode:def__init__(self, data): self.data = data
self.next=None self.prev =Nonedef__str__(self):returnstr(self.data)classLista:def__init__(self): self.head, self.tail=None,Nonedef__len__(self): length =0 current = self.head
while current: length +=1 current = current.nextreturn length
defappend(self, data): new_node = Node(data)if self.head isNone: 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 nodereturnf'{data} has been added'def__str__(self): result =[] current = self.head
while current: result.append(str(current)) current = current.nextreturn' -> '.join(result)+f', tail => {self.tail}'# Add tail information to the string representationdefreverse(self): current = self.head
previous =Nonewhile 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 =>3030->4->3->2->1, tail =>30
classNode:def__init__(self, data): self.data = data
self.next=None self.prev =Nonedef__str__(self):returnstr(self.data)classLista:def__init__(self): self.head, self.tail=None,Nonedef__len__(self): length =0 current = self.head
while current: length +=1 current = current.nextreturn length
defappend(self, data): new_node = Node(data)if self.head isNone: 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 nodereturnf'{data} has been added'def__str__(self): result =[] current = self.head
while current: result.append(str(current)) current = current.nextreturn' -> '.join(result)+f', tail => {self.tail}'# Add tail information to the string representationdefreverse(self): current = self.head
previous =Nonewhile 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)```classNode:def \_\_init\_\_(self, data): self.data = data self.next=None self.prev =Nonedef \_\_str\_\_(self):returnstr(self.data)classLista:def \_\_init\_\_(self): self.head, self.tail=None,None def \_\_len\_\_(self): length =0 current = self.head while current: length +=1 current = current.nextreturn length defappend(self, data): new\_node = Node(data)if self.head isNone: 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
Primera iteración: Movemos el 1 entre 4 y el null
2 -> 3 -> 4 -> 1
Segunda iteración. Movemos el 2 entre el 4 y el 1
3 -> 4 -> 2 -> 1
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.
publicvoidreversarListaEnlazada(){Nodo colaInicial =this.cola;//Guardamos el Nodo cola inicialNodo cabezaInicial =this.cabeza;//Guardamos el Nodo cabeza inicialNodo 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;}}