Dado un puntero al nodo principal de una lista vinculada, la tarea es invertir la lista vinculada. Necesitamos invertir la lista cambiando los enlaces entre los nodos.
Ejemplos :
Práctica recomendada Invertir una lista enlazada ¡Pruébelo!Aporte : Jefe de la siguiente lista enlazada
1->2->3->4->NULO
Producción : La lista vinculada debe cambiarse a,
4->3->2->1->NULOAporte : Jefe de la siguiente lista enlazada
1->2->3->4->5->NULO
Producción : La lista vinculada debe cambiarse a,
5->4->3->2->1->NULOmétodo principal de javaAporte : NULO
Producción : NULO
Aporte : 1->NULO
Producción : 1->NULO
Invertir una lista enlazada por método iterativo:
La idea es utilizar tres consejos. curr , anterior, y próximo para realizar un seguimiento de los nodos para actualizar los enlaces inversos.
Siga los pasos a continuación para resolver el problema:
- Inicializar tres punteros anterior como NULO, curr como cabeza , y próximo como NULO.
- Iterar a través de la lista enlazada. En un bucle, haga lo siguiente:
- Antes de cambiar el próximo de curr , almacenar el próximo nodo
- siguiente = actual -> siguiente
- Ahora actualiza el próximo puntero de curr hacia anterior
- actual -> siguiente = anterior
- Actualizar anterior como curr y curr como próximo
- anterior = actual
- actual = siguiente
- Antes de cambiar el próximo de curr , almacenar el próximo nodo
A continuación se muestra la implementación del enfoque anterior:
C++ // Iterative C++ program to reverse a linked list #include using namespace std; /* Link list node */ struct Node { int data; struct Node* next; Node(int data) { this->datos = datos; siguiente = NULO; } }; struct LinkedList { Nodo* cabeza; ListaEnlazada() { cabeza = NULL; } /* Función para invertir la lista enlazada */ void reverse() { // Inicializa los punteros actual, anterior y siguiente Node* current = head; Nodo *anterior = NULL, *siguiente = NULL; while (actual! = NULL) { // Almacenar siguiente siguiente = actual->siguiente; // Invertir el puntero del nodo actual current->next = prev; // Mueve los punteros una posición hacia adelante. anterior = actual; actual = siguiente; } cabeza = anterior; } /* Función para imprimir la lista enlazada */ void print() { struct Node* temp = head; mientras (temperatura! = NULL) { cout<< temp->datos<< ' '; temp = temp->próximo; } } void push(int datos) { Nodo* temp = nuevo Nodo(datos); temp->siguiente = cabeza; cabeza = temperatura; } }; /* Código del controlador*/ int main() { /* Comience con la lista vacía */ LinkedList ll; ll.push(20); ll.push(4); ll.push(15); ll.push(85); corte<< 'Given linked list
'; ll.print(); ll.reverse(); cout << '
Reversed linked list
'; ll.print(); return 0; }> C // Iterative C program to reverse a linked list #include #include /* Link list node */ struct Node { int data; struct Node* next; }; /* Function to reverse the linked list */ static void reverse(struct Node** head_ref) { struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next = NULL; while (current != NULL) { // Store next next = current->próximo; // Invertir el puntero del nodo actual current->next = prev; // Mueve los punteros una posición hacia adelante. anterior = actual; actual = siguiente; } *head_ref = anterior; } /* Función para empujar un nodo */ void push(struct Node** head_ref, int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); nuevo_nodo->datos = nuevos_datos; nuevo_nodo->siguiente = (*head_ref); (*head_ref) = nuevo_nodo; } /* Función para imprimir la lista enlazada */ void printList(struct Node* head) { struct Node* temp = head; while (temp != NULL) { printf('%d ', temp->datos); temperatura = temperatura->siguiente; } } /* Código del controlador*/ int main() { /* Comience con la lista vacía */ struct Node* head = NULL; empujar(&cabeza, 20); empujar(&cabeza, 4); empujar(&cabeza, 15); empujar(&cabeza, 85); printf('Lista enlazada dada
'); imprimirLista(cabeza); marcha atrás (& cabeza); printf('
Lista enlazada invertida
'); imprimirLista(cabeza); getchar(); }> Java // Java program for reversing the linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to reverse the linked list */ Node reverse(Node node) { Node prev = null; Node current = node; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } node = prev; return node; } // prints content of double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + ' '); node = node.next; } } // Driver Code public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(85); list.head.next = new Node(15); list.head.next.next = new Node(4); list.head.next.next.next = new Node(20); System.out.println('Given linked list'); list.printList(head); head = list.reverse(head); System.out.println(''); System.out.println('Reversed linked list '); list.printList(head); } } // This code has been contributed by Mayank Jaiswal> Pitón # Python program to reverse a linked list # Time Complexity : O(n) # Space Complexity : O(1) # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to reverse the linked list def reverse(self): prev = None current = self.head while(current is not None): next = current.next current.next = prev prev = current current = next self.head = prev # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the LinkedList def printList(self): temp = self.head while(temp): print(temp.data, end=' ') temp = temp.next # Driver code llist = LinkedList() llist.push(20) llist.push(4) llist.push(15) llist.push(85) print ('Given linked list') llist.printList() llist.reverse() print ('
Reversed linked list') llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)> C# // C# program for reversing the linked list using System; class GFG { // Driver Code static void Main(string[] args) { LinkedList list = new LinkedList(); list.AddNode(new LinkedList.Node(85)); list.AddNode(new LinkedList.Node(15)); list.AddNode(new LinkedList.Node(4)); list.AddNode(new LinkedList.Node(20)); // List before reversal Console.WriteLine('Given linked list '); list.PrintList(); // Reverse the list list.ReverseList(); // List after reversal Console.WriteLine('Reversed linked list '); list.PrintList(); } } class LinkedList { Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // function to add a new node at // the end of the list public void AddNode(Node node) { if (head == null) head = node; else { Node temp = head; while (temp.next != null) { temp = temp.next; } temp.next = node; } } // function to reverse the list public void ReverseList() { Node prev = null, current = head, next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head = prev; } // function to print the list data public void PrintList() { Node current = head; while (current != null) { Console.Write(current.data + ' '); current = current.next; } Console.WriteLine(); } } // This code is contributed by Mayank Sharma> JavaScript >
Producción
Given linked list 85 15 4 20 Reversed linked list 20 4 15 85>
Complejidad del tiempo: O (N), atravesando la lista vinculada de tamaño N.
Espacio Auxiliar: O(1)
Invertir una lista enlazada usando recursividad:
La idea es llegar al último nodo de la lista vinculada mediante recursividad y luego comenzar a invertir la lista vinculada.
método principal de java
Siga los pasos a continuación para resolver el problema:
- Divida la lista en dos partes: el primer nodo y el resto de la lista vinculada.
- Llame a la inversa para el resto de la lista vinculada.
- Vincula el resto de la lista vinculada al primero.
- Fijar el puntero principal a NULL
A continuación se muestra la implementación del enfoque anterior:
C++ // Recursive C++ program to reverse // a linked list #include using namespace std; /* Link list node */ struct Node { int data; struct Node* next; Node(int data) { this->datos = datos; siguiente = NULO; } }; struct LinkedList { Nodo* cabeza; ListaEnlazada() { cabeza = NULL; } Nodo* reverso(Nodo* cabeza) /* Función para imprimir la lista enlazada */ void print() { struct Nodo* temp = cabeza; mientras (temperatura! = NULL) { cout<< temp->datos<< ' '; temp = temp->próximo; } } void push(int datos) { Nodo* temp = nuevo Nodo(datos); temp->siguiente = cabeza; cabeza = temperatura; } }; /* Programa controlador para probar la función anterior*/ int main() { /* Comience con la lista vacía */ LinkedList ll; ll.push(20); ll.push(4); ll.push(15); ll.push(85); corte<< 'Given linked list
'; ll.print(); ll.head = ll.reverse(ll.head); cout << '
Reversed linked list
'; ll.print(); return 0; }> Java // Recursive Java program to reverse // a linked list import java.io.*; class recursion { static Node head; // head of list static class Node { int data; Node next; Node(int d) { data = d; next = null; } } static Node reverse(Node head) /* Function to print linked list */ static void print() { Node temp = head; while (temp != null) { System.out.print(temp.data + ' '); temp = temp.next; } System.out.println(); } static void push(int data) { Node temp = new Node(data); temp.next = head; head = temp; } /* Driver program to test above function*/ public static void main(String args[]) { /* Start with the empty list */ push(20); push(4); push(15); push(85); System.out.println('Given linked list'); print(); head = reverse(head); System.out.println('Reversed linked list'); print(); } } // This code is contributed by Prakhar Agarwal> Pitón '''Python3 program to reverse linked list using recursive method''' # Linked List Node class Node: def __init__(self, data): self.data = data self.next = None # Create and Handle list operations class LinkedList: def __init__(self): self.head = None # Head of list # Method to reverse the list def reverse(self, head): # If head is empty or has reached the list end if head is None or head.next is None: return head # Reverse the rest list rest = self.reverse(head.next) # Put first element at the end head.next.next = head head.next = None # Fix the header pointer return rest # Returns the linked list in display format def __str__(self): linkedListStr = '' temp = self.head while temp: linkedListStr = (linkedListStr + str(temp.data) + ' ') temp = temp.next return linkedListStr # Pushes new data to the head of the list def push(self, data): temp = Node(data) temp.next = self.head self.head = temp # Driver code linkedList = LinkedList() linkedList.push(20) linkedList.push(4) linkedList.push(15) linkedList.push(85) print('Given linked list') print(linkedList) linkedList.head = linkedList.reverse(linkedList.head) print('Reversed linked list') print(linkedList) # This code is contributed by Debidutta Rath> C# // Recursive C# program to // reverse a linked list using System; class recursion { // Head of list static Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } static Node reverse(Node head) if (head == null // Function to print linked list static void print() { Node temp = head; while (temp != null) { Console.Write(temp.data + ' '); temp = temp.next; } Console.WriteLine(); } static void push(int data) { Node temp = new Node(data); temp.next = head; head = temp; } // Driver code public static void Main(String[] args) { // Start with the // empty list push(20); push(4); push(15); push(85); Console.WriteLine('Given linked list'); print(); head = reverse(head); Console.WriteLine('Reversed linked list'); print(); } } // This code is contributed by gauravrajput1> JavaScript >
Producción
Given linked list 85 15 4 20 Reversed linked list 20 4 15 85>
Complejidad del tiempo: O(N), visitando cada nodo una vez
Espacio Auxiliar: O (N), espacio de pila de llamadas de función
Invertir una lista enlazada mediante el método recursivo Tail:
La idea es mantener tres punteros. anterior , actual y próximo , visite recursivamente cada nodo y cree enlaces utilizando estos tres punteros.
Siga los pasos a continuación para resolver el problema:
operadores javascript
- Primera actualización a continuación con el siguiente nodo de la corriente, es decir. siguiente = actual->siguiente
- Ahora haga un enlace inverso desde el nodo actual al nodo anterior, es decir, curr->next = prev
- Si el nodo visitado es el último nodo, simplemente haga un enlace inverso desde el nodo actual al nodo anterior y actualice el encabezado.
A continuación se muestra la implementación del enfoque anterior:
C++ // A simple and tail recursive C++ program to reverse // a linked list #include using namespace std; struct Node { int data; struct Node* next; Node(int x) { data = x; next = NULL; } }; void reverseUtil(Node* curr, Node* prev, Node** head); // This function mainly calls reverseUtil() // with prev as NULL void reverse(Node** head) { if (!head) return; reverseUtil(*head, NULL, head); } // A simple and tail-recursive function to reverse // a linked list. prev is passed as NULL initially. void reverseUtil(Node* curr, Node* prev, Node** head) { /* If last node mark it head*/ if (!curr->siguiente) { *head = curr; /* Actualizar junto al nodo anterior */ curr->next = prev; devolver; } /* Guardar actual->siguiente nodo para llamada recursiva */ Nodo* siguiente = curr->siguiente; /* y actualiza el siguiente ..*/ curr->next = prev; ReverseUtil(siguiente, curr, cabeza); } // Una función de utilidad para imprimir una lista vinculada void printlist(Node* head) { while (head != NULL) { cout<< head->datos<< ' '; head = head->próximo; } escucha<< endl; } // Driver code int main() { Node* head1 = new Node(1); head1->siguiente = nuevo Nodo(2); encabezado1->siguiente->siguiente = nuevo Nodo(3); head1->siguiente->siguiente->siguiente = nuevo Nodo(4); head1->siguiente->siguiente->siguiente->siguiente = nuevo Nodo(5); head1->siguiente->siguiente->siguiente->siguiente->siguiente = nuevo Nodo(6); head1->siguiente->siguiente->siguiente->siguiente->siguiente->siguiente = nuevo Nodo(7); head1->siguiente->siguiente->siguiente->siguiente->siguiente->siguiente->siguiente = nuevo Nodo(8); corte<< 'Given linked list
'; printlist(head1); reverse(&head1); cout << 'Reversed linked list
'; printlist(head1); return 0; }> C // A simple and tail recursive C program to reverse a linked // list #include #include typedef struct Node { int data; struct Node* next; } Node; void reverseUtil(Node* curr, Node* prev, Node** head); // This function mainly calls reverseUtil() // with prev as NULL void reverse(Node** head) { if (!head) return; reverseUtil(*head, NULL, head); } // A simple and tail-recursive function to reverse // a linked list. prev is passed as NULL initially. void reverseUtil(Node* curr, Node* prev, Node** head) { /* If last node mark it head*/ if (!curr->siguiente) { *head = curr; /* Actualizar junto al nodo anterior */ curr->next = prev; devolver; } /* Guardar actual->siguiente nodo para llamada recursiva */ Nodo* siguiente = curr->siguiente; /* y actualiza el siguiente ..*/ curr->next = prev; ReverseUtil(siguiente, curr, cabeza); } // Una función de utilidad para crear un nuevo nodo Node* newNode(int key) { Node* temp = (Node*)malloc(sizeof(Node)); temperatura->datos = clave; temperatura->siguiente = NULL; temperatura de retorno; } // Una función de utilidad para imprimir una lista enlazada void printlist(Node* head) { while (head != NULL) { printf('%d ', head->data); cabeza = cabeza->siguiente; } printf('
'); } // Código del controlador int main() { Nodo* cabeza1 = nuevoNodo(1); encabezado1->siguiente = nuevoNodo(2); encabezado1->siguiente->siguiente = nuevoNodo(3); encabezado1->siguiente->siguiente->siguiente = nuevoNodo(4); head1->siguiente->siguiente->siguiente->siguiente = newNode(5); head1->siguiente->siguiente->siguiente->siguiente->siguiente = newNode(6); head1->siguiente->siguiente->siguiente->siguiente->siguiente->siguiente = newNode(7); head1->siguiente->siguiente->siguiente->siguiente->siguiente->siguiente->siguiente = newNode(8); printf('Lista enlazada dada
'); lista de impresión (cabeza1); marcha atrás(&cabeza1); printf('Lista enlazada invertida
'); lista de impresión (cabeza1); devolver 0; } // Este código es una contribución de Aditya Kumar (adityakumar129)> Java // Java program for reversing the Linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } // A simple and tail recursive function to reverse // a linked list. prev is passed as NULL initially. Node reverseUtil(Node curr, Node prev) { /*If head is initially null OR list is empty*/ if (head == null) return head; /* If last node mark it head*/ if (curr.next == null) { head = curr; /* Update next to prev node */ curr.next = prev; return head; } /* Save curr->siguiente nodo para llamada recursiva */ Nodo next1 = curr.next; /* y actualizar siguiente ..*/ curr.next = prev; ReverseUtil(siguiente1, curr); cabeza de retorno; } // imprime el contenido de la lista doblemente enlazada void printList(Node node) { while (node!= null) { System.out.print(node.data + ' '); nodo = nodo.siguiente; } } // Código del controlador public static void main(String[] args) { lista LinkedList = new LinkedList(); list.head = nuevo Nodo(1); list.head.next = nuevo Nodo(2); list.head.next.next = nuevo Nodo(3); list.head.next.next.next = nuevo Nodo(4); list.head.next.next.next.next = nuevo Nodo(5); list.head.next.next.next.next.next = nuevo Nodo(6); list.head.next.next.next.next.next.next = nuevo Nodo(7); list.head.next.next.next.next.next.next.next = nuevo Nodo(8); System.out.println('Lista enlazada dada '); lista.printList(cabeza); Nodo res = list.reverseUtil(head, null); System.out.println('
Lista enlazada invertida '); lista.printList(res); } } // Este código es una contribución de Aditya Kumar (adityakumar129)> Pitón # Simple and tail recursive Python program to # reverse a linked list # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None def reverseUtil(self, curr, prev): # If last node mark it head if curr.next is None: self.head = curr # Update next to prev node curr.next = prev return # Save curr.next node for recursive call next = curr.next # And update next curr.next = prev self.reverseUtil(next, curr) # This function mainly calls reverseUtil() # with previous as None def reverse(self): if self.head is None: return self.reverseUtil(self.head, None) # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data, end=' ') temp = temp.next # Driver code llist = LinkedList() llist.push(8) llist.push(7) llist.push(6) llist.push(5) llist.push(4) llist.push(3) llist.push(2) llist.push(1) print ('Given linked list') llist.printList() llist.reverse() print ('
Reversed linked list') llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)> C# // C# program for reversing the Linked list using System; public class LinkedList { Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // A simple and tail-recursive function to reverse // a linked list. prev is passed as NULL initially. Node reverseUtil(Node curr, Node prev) { /* If last node mark it head*/ if (curr.next == null) { head = curr; /* Update next to prev node */ curr.next = prev; return head; } /* Save curr->siguiente nodo para llamada recursiva */ Nodo next1 = curr.next; /* y actualizar siguiente ..*/ curr.next = prev; ReverseUtil(siguiente1, curr); cabeza de retorno; } // imprime el contenido de la lista doblemente enlazada void printList(Node node) { while (node!= null) { Console.Write(node.data + ' '); nodo = nodo.siguiente; } } // Código del controlador public static void Main(String[] args) { lista LinkedList = new LinkedList(); list.head = nuevo Nodo(1); list.head.next = nuevo Nodo(2); list.head.next.next = nuevo Nodo(3); list.head.next.next.next = nuevo Nodo(4); list.head.next.next.next.next = nuevo Nodo(5); list.head.next.next.next.next.next = nuevo Nodo(6); list.head.next.next.next.next.next.next = nuevo Nodo(7); list.head.next.next.next.next.next.next.next = nuevo Nodo(8); Console.WriteLine('Lista enlazada dada '); lista.printList(lista.cabeza); Nodo res = list.reverseUtil(list.head, null); Console.WriteLine('
Lista enlazada invertida '); lista.printList(res); } } // Este código fue aportado por Rajput-Ji> JavaScript >
Producción
Given linked list 1 2 3 4 5 6 7 8 Reversed linked list 8 7 6 5 4 3 2 1>
Complejidad del tiempo: O (N), visitando cada nodo de la lista enlazada de tamaño N.
Espacio Auxiliar: O (N), espacio de pila de llamadas de función
Invertir una lista enlazada usando La idea es almacenar todos los nodos en la pila y luego hacer una lista con enlace inverso.
Siga los pasos a continuación para resolver el problema:
- Almacene los nodos (valores y dirección) en la pila hasta que se ingresen todos los valores.
- Una vez realizadas todas las entradas, actualice el puntero principal a la última ubicación (es decir, el último valor).
- Comience a extraer los nodos (valor y dirección) y guárdelos en el mismo orden hasta que la pila esté vacía.
- Actualice el siguiente puntero del último nodo de la pila mediante NULL.
A continuación se muestra la implementación del enfoque anterior:
C++ // C++ program for above approach #include #include using namespace std; // Create a class Node to enter values and address in the // list class Node { public: int data; Node* next; Node(int x) { data = x; next = NULL; } }; // Function to reverse the linked list void reverseLL(Node** head) { // Create a stack 's' of Node type stacks; Nodo* temp = *cabeza; while (temp->next != NULL) { // Empuja todos los nodos para apilar s.push(temp); temperatura = temperatura->siguiente; } *cabeza = temperatura; while (!s.empty()) { // Almacena el valor superior de la pila en la lista temp->next = s.top(); // Extrae el valor de la pila s.pop(); // actualiza el siguiente puntero en la lista temp = temp->next; } temporal->siguiente = NULL; } // Función para mostrar los elementos en la lista void printlist(Node* temp) { while (temp != NULL) { cout<< temp->datos<< ' '; temp = temp->próximo; } } // Programa para insertar la parte posterior de la lista vinculada void insert_back(Node** head, int value) { // hemos utilizado el método de inserción en la parte posterior para ingresar valores // en la lista. (por ejemplo: head->1->2->3->4->Nulo) Nodo* temp = nuevo Nodo(valor); temperatura->siguiente = NULL; // Si *head es igual a NULL if (*head == NULL) { *head = temp; devolver; } else { Nodo* último_nodo = *cabeza; mientras (último_nodo->siguiente! = NULL) último_nodo = último_nodo->siguiente; último_nodo->siguiente = temporal; devolver; } } // Código del controlador int main() { Nodo* head = NULL; insert_back(&cabeza, 1); insert_back(&cabeza, 2); insert_back(&cabeza, 3); insert_back(&cabeza, 4); corte<< 'Given linked list
'; printlist(head); reverseLL(&head); cout << '
Reversed linked list
'; printlist(head); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)> Java // Java program for above approach import java.util.*; class GFG { // Create a class Node to enter values and address in // the list static class Node { int data; Node next; Node(int x) { data = x; next = null; } }; static Node head = null; // Function to reverse the linked list static void reverseLL() { // Create a stack 's' of Node type Stacks = nueva pila(); Temperatura del nodo = cabeza; while (temp.next! = null) { // Empuja todos los nodos para apilar s.add(temp); temp = temp.siguiente; } cabeza = temperatura; while (!s.isEmpty()) { // Almacena el valor superior de la pila en la lista temp.next = s.peek(); // Extrae el valor de la pila s.pop(); // actualiza el siguiente puntero de la lista temp = temp.next; } temp.siguiente = nulo; } // Función para mostrar los elementos en la lista static void printlist(Node temp) { while (temp!= null) { System.out.print(temp.data + ' '); temp = temp.siguiente; } } // Programa para insertar la parte posterior de la lista vinculada static void insert_back(int value) { // hemos utilizado el método de inserción en la parte posterior para ingresar // valores en la lista. (por ejemplo: head.1.2.3.4.Null) Nodo temp = nuevo nodo (valor); temp.siguiente = nulo; // Si *head es igual a nulo if (head == null) { head = temp; devolver; } else { Nodo último_nodo = cabeza; mientras (último_nodo.siguiente! = nulo) último_nodo = último_nodo.siguiente; último_nodo.siguiente = temporal; devolver; } } // Código del controlador public static void main(String[] args) { insert_back(1); insertar_back(2); insertar_back(3); insertar_back(4); System.out.print('Lista enlazada dada
'); lista de impresión (cabeza); inversaLL(); System.out.print('
Lista enlazada invertida
'); lista de impresión (cabeza); } } // Este código es una contribución de Aditya Kumar (adityakumar129)> Pitón # Python code for the above approach # Definition for singly-linked list. class ListNode: def __init__(self, val = 0, next=None): self.val = val self.next = next class Solution: # Program to reverse the linked list # using stack def reverseLLUsingStack(self, head): # Initialise the variables stack, temp = [], head while temp: stack.append(temp) temp = temp.next head = temp = stack.pop() # Until stack is not # empty while len(stack)>0: temp.next = stack.pop() temp = temp.next temp.next = Ninguno return head # Código de controlador if __name__ == '__main__': head = ListNode(1, ListNode(2, ListNode(3, ListNode(4)))) print('Lista enlazada dada') temp = head while temp: print(temp.val, end=' ') temp = temp.next obj = Solution() print('
Lista enlazada invertida') head = obj.reverseLLUsingStack(head) mientras que head: print(head.val, end=' ') head = head.next> C# // C# program for above approach using System; using System.Collections.Generic; class GFG { // Create a class Node to enter // values and address in the list public class Node { public int data; public Node next; public Node(int x) { data = x; } }; static Node head = null; // Function to reverse the // linked list static void reverseLL() { // Create a stack 's' // of Node type Stacks = nueva pila(); Temperatura del nodo = cabeza; while (temp.next != null) { // Empuja todos los nodos // hacia la pila s.Push(temp); temp = temp.siguiente; } cabeza = temperatura; while (s.Count != 0) { // Almacena el valor superior de // la pila en la lista temp.next = s.Peek(); // Extrae el valor de la pila s.Pop(); // Actualiza el siguiente puntero en // la lista temp = temp.next; } temp.siguiente = nulo; } // Función para mostrar // los elementos en la lista static void printlist(Node temp) { while (temp != null) { Console.Write(temp.data + ' '); temp = temp.siguiente; } } // Función para insertar atrás de la // lista enlazada static void insert_back(int val) { // Hemos utilizado el método de inserción atrás // para ingresar valores en la lista. (por ejemplo: // head.1.2.3.4 .Null) Temperatura del nodo = nuevo nodo(val); temp.siguiente = nulo; // Si *head es igual a nulo if (head == null) { head = temp; devolver; } else { Nodo último_nodo = cabeza; while (último_nodo.siguiente! = nulo) { último_nodo = último_nodo.siguiente; } último_nodo.siguiente = temporal; devolver; } } // Código del controlador public static void Main(String[] args) { insert_back(1); insertar_back(2); insertar_back(3); insertar_back(4); Console.Write('Lista enlazada dada
'); lista de impresión (cabeza); inversaLL(); Console.Write('
Lista enlazada invertida
'); lista de impresión (cabeza); } } // Este código es una contribución de gauravrajput1> JavaScript >
Producción
Given linked list 1 2 3 4 Reversed linked list 4 3 2 1>
Complejidad del tiempo: O (N), visitando cada nodo de la lista enlazada de tamaño N.
Espacio Auxiliar: O (N), el espacio se utiliza para almacenar los nodos en la pila.