Donat un punter al node principal d'una llista enllaçada, la tasca és invertir la llista enllaçada. Hem d'invertir la llista canviant els enllaços entre nodes.
Exemples :
Pràctica recomanada Invertir una llista enllaçada Prova-ho!Entrada : Cap de la següent llista enllaçada
1->2->3->4->NULL
Sortida : la llista enllaçada s'ha de canviar a,
4->3->2->1->NULLEntrada : Cap de la següent llista enllaçada
1->2->3->4->5->NULL
Sortida : la llista enllaçada s'ha de canviar a,
5->4->3->2->1->NULLmètode de subcadenes de JavaEntrada : NUL
Sortida : NUL
Entrada : 1->NULL
Sortida : 1->NULL
Inverteix una llista enllaçada per mètode iteratiu:
La idea és utilitzar tres punters curr , anterior, i Pròxim per fer un seguiment dels nodes per actualitzar els enllaços inversos.
Seguiu els passos següents per resoldre el problema:
- Inicialitzar tres punters anterior com a NULL, curr com cap , i Pròxim com a NULL.
- Itera per la llista enllaçada. En un bucle, feu el següent:
- Abans de canviar el Pròxim de curr , emmagatzemar el Pròxim node
- següent = curr -> següent
- Ara actualitzeu el Pròxim punter de curr fins al anterior
- curr -> següent = anterior
- Actualització anterior com curr i curr com Pròxim
- prev = curr
- curr = següent
- Abans de canviar el Pròxim de curr , emmagatzemar el Pròxim node
A continuació es mostra la implementació de l'enfocament anterior:
creant taules en làtexC++
// 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->dades = dades; següent = NULL; }}; struct LinkedList { Node* cap; LinkedList() { cap = NULL; } /* Funció per invertir la llista enllaçada */ void reverse() { // Inicialitzar els punters actuals, anteriors i següents Node* current = cap; Node *prev = NULL, *next = NULL; while (actual != NULL) { // Desa següent següent = actual->següent; // Invertir el punter actual del node actual->next = prev; // Mou els punters una posició per davant. prev = actual; actual = següent; } cap = anterior; } /* Funció per imprimir la llista enllaçada */ void print() { struct Node* temp = head; while (temp != NULL) { cout<< temp->dades<< ' '; temp = temp->Pròxim; } } void push (dades int) { Node* temp = nou Node (dades); temp->següent = cap; cap = temperatura; }}; /* Codi del controlador*/ int main() { /* Comença amb la llista buida */ LinkedList ll; ll.push(20); ll.push(4); ll.push(15); ll.push(85); cout<< '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òxim; // Invertir el punter actual del node actual->next = prev; // Mou els punters una posició per davant. prev = actual; actual = següent; } *head_ref = anterior; } /* Funció per empènyer un node */ void push(struct Node** head_ref, int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); nou_node->dades = noves_dades; nou_node->següent = (*head_ref); (*head_ref) = nou_node; } /* Funció per imprimir la llista enllaçada */ void printList(struct Node* head) { struct Node* temp = head; while (temp != NULL) { printf('%d', temp->data); temp = temp->següent; } } /* Codi del controlador*/ int main() { /* Comença amb la llista buida */ struct Node* head = NULL; empenta(&cap, 20); empenta(&cap, 4); empenta(&cap, 15); empenta(&cap, 85); printf('Llista enllaçada donada
'); printList(capçal); revés(&cap); printf('
Llista enllaçada invertida
'); printList(capçal); getchar(); }>>>Java Python # 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 >
Sortida
Given linked list 85 15 4 20 Reversed linked list 20 4 15 85>
Complexitat temporal: O (N), recorrent la llista enllaçada de mida N.
Espai auxiliar: O(1)
Inverteix una llista enllaçada amb recursivitat:
La idea és arribar a l'últim node de la llista enllaçada mitjançant recursivitat i després començar a invertir la llista enllaçada.
Seguiu els passos següents per resoldre el problema:
- Dividiu la llista en dues parts: el primer node i la resta de la llista enllaçada.
- Truqueu al revés per a la resta de la llista enllaçada.
- Enllaceu primer la resta de la llista enllaçada.
- Fixeu el punter del cap a NULL
A continuació es mostra la implementació de l'enfocament 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->dades = dades; següent = NULL; }}; struct LinkedList { Node* cap; Llista Enllaçada () { cap = NULL; } Node* reverse(Node* cap) /* Funció per imprimir la llista enllaçada */ void print() { struct Node* temp = cap; while (temp != NULL) { cout<< temp->dades<< ' '; temp = temp->Pròxim; } } void push (dades int) { Node* temp = nou Node (dades); temp->següent = cap; cap = temperatura; }}; /* Programa de controlador per provar la funció anterior*/ int main() { /* Comença amb la llista buida */ LinkedList ll; ll.push(20); ll.push(4); ll.push(15); ll.push(85); cout<< '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> Python '''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 >
Sortida
Given linked list 85 15 4 20 Reversed linked list 20 4 15 85>
Complexitat temporal: O(N), visitant cada node una vegada
Espai auxiliar: O(N), espai de pila de trucades de funció
Inverteix una llista enllaçada mitjançant el mètode recursiu de la cua:
La idea és mantenir tres punts anterior , actual i Pròxim , visiteu de manera recursiva tots els nodes i feu enllaços amb aquests tres punters.
Seguiu els passos següents per resoldre el problema:
iterant un mapa en java
- Primera actualització següent amb el següent node actual, és a dir. següent = actual->següent
- Ara feu un enllaç invers des del node actual al node anterior, és a dir, curr->next = prev
- Si el node visitat és l'últim node, feu un enllaç invers des del node actual al node anterior i actualitzeu el cap.
A continuació es mostra la implementació de l'enfocament 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->següent) { *cap = curr; /* Actualitza al costat del node anterior */ curr->next = prev; tornar; } /* Desa curr->next node per a la trucada recursiva */ Node* next = curr->next; /* i actualitzeu el següent ..*/ curr->next = prev; reverseUtil(següent, curr, cap); } // Una funció d'utilitat per imprimir una llista enllaçada void printlist (Node* head) { while (head != NULL) { cout<< head->dades<< ' '; head = head->Pròxim; } cout<< endl; } // Driver code int main() { Node* head1 = new Node(1); head1->següent = nou Node (2); head1->next->next = nou Node (3); head1->next->next->next = nou Node (4); head1->next->next->next->next = nou Node (5); cap1->següent->següent->següent->següent->següent = nou Node (6); head1->next->next->next->next->next->next = nou Node (7); head1->next->next->next->next->next->next->next = nou Node (8); cout<< '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->següent) { *cap = curr; /* Actualitza al costat del node anterior */ curr->next = prev; tornar; } /* Desa curr->next node per a la trucada recursiva */ Node* next = curr->next; /* i actualitzeu el següent ..*/ curr->next = prev; reverseUtil(següent, curr, cap); } // Una funció d'utilitat per crear un nou node Node* newNode(clau int) { Node* temp = (Node*)malloc(sizeof(Node)); temp->data = clau; temp->següent = NULL; temperatura de retorn; } // Una funció d'utilitat per imprimir una llista enllaçada void printlist(Node* head) { while (head != NULL) { printf('%d ', head->data); cap = cap->següent; } printf('
'); } // Codi del controlador int main() { Node* cap1 = nouNode(1); cap1->següent = nouNode(2); cap1->següent->següent = nouNode(3); head1->next->next->next = nouNode(4); head1->next->next->next->next = nouNode(5); head1->next->next->next->next->next = nouNode(6); head1->next->next->next->next->next->next = nouNode(7); head1->next->next->next->next->next->next->next = nouNode(8); printf('Llista enllaçada donada
'); llista d'impressió(cap1); revés(&cap1); printf('Llista enllaçada invertida
'); llista d'impressió (capçalera1); retorn 0; } // Aquest codi és aportat per Aditya Kumar (adityakumar129)>>>Java>> Python 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->següent node per a trucades recursives */ Node next1 = curr.next; /* i actualitzeu el següent ..*/ curr.next = anterior; reverseUtil(següent1, curr); cap de retorn; } // imprimeix el contingut de la llista doble enllaçada void printList(Node node) { while (node != null) { Console.Write(node.data + ' '); node = node.next; } } // Codi del controlador public static void Main(String[] args) { LinkedList list = new LinkedList(); list.head = nou Node (1); list.head.next = nou Node (2); list.head.next.next = nou Node (3); list.head.next.next.next = nou Node (4); list.head.next.next.next.next = nou Node (5); list.head.next.next.next.next.next.next = nou Node (6); list.head.next.next.next.next.next.next.next = nou Node (7); list.head.next.next.next.next.next.next.next.next = nou Node (8); Console.WriteLine('Llista enllaçada donada'); list.printList(list.head); Node res = list.reverseUtil (list.head, null); Console.WriteLine('
Llista enllaçada invertida '); list.printList(res); } } // Aquest codi aportat per Rajput-Ji>>>Javascriptnext node per a la trucada recursiva */ var next1 = curr.next; /* i actualitzeu el següent .. */ curr.next = anterior; reverseUtil(següent1, curr); cap de retorn; } // imprimeix el contingut de la funció de llista enllaçada var printList(node) { while (node != null) { document.write(node.data + ' '); node = node.next; } } // Codi del controlador var head = nou Node(1); head.next = nou Node (2); head.next.next = nou Node (3); head.next.next.next = nou Node (4); head.next.next.next.next = nou Node (5); head.next.next.next.next.next = nou Node (6); head.next.next.next.next.next.next.next = nou Node (7); head.next.next.next.next.next.next.next.next = nou Node (8); document.write('Llista enllaçada original'); printList(capçal); var res = reverseUtil(cap, null); document.write(' '); document.write('Llista enllaçada invertida'); printList(res); // Aquest codi és aportat per Rajput-Ji> Sortida
Given linked list 1 2 3 4 5 6 7 8 Reversed linked list 8 7 6 5 4 3 2 1>
Complexitat temporal: O (N), visitant tots els nodes de la llista enllaçada de mida N.
Espai auxiliar: O(N), espai de pila de trucades de funció
Invertir una llista enllaçada utilitzant La idea és emmagatzemar tots els nodes de la pila i després fer una llista enllaçada inversament.
Seguiu els passos següents per resoldre el problema:
- Emmagatzemeu els nodes (valors i adreça) a la pila fins que s'introdueixin tots els valors.
- Un cop fetes totes les entrades, actualitzeu el punter Cap a l'última ubicació (és a dir, l'últim valor).
- Comenceu a aparèixer els nodes (valor i adreça) i deseu-los en el mateix ordre fins que la pila estigui buida.
- Actualitzeu el punter següent de l'últim node de la pila per NULL.
A continuació es mostra la implementació de l'enfocament 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; Node* temp = *cap; while (temp->next != NULL) { // Empènyer tots els nodes per apilar s.push(temp); temp = temp->següent; } *cap = temperatura; while (!s.empty()) { // Emmagatzema el valor superior de la pila a la llista temp->next = s.top(); // Desplega el valor de la pila s.pop(); // actualitza el punter següent a la llista temp = temp->next; } temp->next = NULL; } // Funció per mostrar els elements a List void printlist(Node* temp) { while (temp != NULL) { cout<< temp->dades<< ' '; temp = temp->Pròxim; } } // Programa per inserir la part posterior de la llista enllaçada void insert_back(Node** head, int value) { // hem utilitzat el mètode d'inserció al darrere per introduir valors // a la llista. (per exemple: head->1->2->3->4->Nul) Node* temp = nou Node (valor); temp->següent = NULL; // Si *head és igual a NULL if (*head == NULL) { *head = temp; tornar; } else { Node* últim_node = *cap; mentre que (últim_node->següent != NULL) últim_node = últim_node->següent; last_node->next = temp; tornar; } } // Codi del controlador int main() { Node* cap = NULL; insert_back(&cap, 1); insert_back(&cap, 2); insert_back(&cap, 3); insert_back(&cap, 4); cout<< '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 = nova pila (); Node temp = cap; while (temp.next != null) { // Empènyer tots els nodes per apilar s.add(temp); temp = temp.següent; } cap = temperatura; while (!s.isEmpty()) { // Emmagatzema el valor superior de la pila a la llista temp.next = s.peek(); // Desplega el valor de la pila s.pop(); // actualitza el punter següent a la llista temp = temp.next; } temp.next = nul; } // Funció per mostrar els elements a List static void printlist(Node temp) { while (temp != null) { System.out.print(temp.data + ' '); temp = temp.següent; } } // Programa per inserir la part posterior de la llista enllaçada static void insert_back(int value) { // hem utilitzat el mètode d'inserció al darrere per introduir // valors a la llista. (per exemple: head.1.2.3.4.Null) Node temp = nou Node (valor); temp.next = nul; // Si *cap és igual a nul if (cap == nul) { cap = temp; tornar; } else { Node last_node = cap; mentre que (últim_node.següent != nul) últim_node = últim_node.següent; last_node.next = temp; tornar; } } // Codi del controlador public static void main(String[] args) { insert_back(1); insert_back(2); insert_back(3); insert_back(4); System.out.print('Llista enllaçada donada
'); llista d'impressió (capçal); reverseLL(); System.out.print('
Llista enllaçada invertida
'); llista d'impressió (capçal); } } // Aquest codi és aportat per Aditya Kumar (adityakumar129)>>>Python 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 = nova pila(); Node temp = cap; while (temp.next != null) { // Empènyer tots els nodes // per apilar s.Push(temp); temp = temp.següent; } cap = temperatura; while (s.Count != 0) { // Emmagatzema el valor superior de // pila a la llista temp.next = s.Peek(); // Desplega el valor de la pila s.Pop(); // Actualitza el punter següent a // a la llista temp = temp.next; } temp.next = nul; } // Funció per mostrar // els elements de List static void printlist(Node temp) { while (temp != null) { Console.Write(temp.data + ' '); temp = temp.següent; } } // Funció per inserir la part posterior de la // llista enllaçada static void insert_back(int val) { // Hem utilitzat el mètode d'inserció al darrere // per introduir valors a la llista. (per exemple: // head.1.2.3.4 .Null) Node temp = new Node(val); temp.next = nul; // Si *cap és igual a nul if (cap == nul) { cap = temp; tornar; } else { Node últim_node = cap; mentre que (últim_node.següent != nul) { darrer_node = darrer_node.següent; } last_node.next = temp; tornar; } } // Codi del controlador public static void Main(String[] args) { insert_back(1); insert_back(2); insert_back(3); insert_back(4); Console.Write('Llista enllaçada donada
'); llista d'impressió (capçal); reverseLL(); Console.Write('
Llista enllaçada invertida
'); llista d'impressió (capçal); } } // Aquest codi és aportat per gauravrajput1> Javascript >
Sortida
Given linked list 1 2 3 4 Reversed linked list 4 3 2 1>
Complexitat temporal: O (N), visitant tots els nodes de la llista enllaçada de mida N.
Espai auxiliar: O(N), l'espai s'utilitza per emmagatzemar els nodes a la pila.