Mając wskaźnik do węzła głównego połączonej listy, zadaniem jest odwrócenie połączonej listy. Musimy odwrócić listę, zmieniając połączenia między węzłami.
Przykłady :
Zalecana praktyka Odwracanie połączonej listy Wypróbuj!Wejście : Szef następującej listy połączonej
1->2->3->4->NULL
Wyjście : Lista połączona powinna zostać zmieniona na,
4->3->2->1->NULLWejście : Szef następującej listy połączonej
1->2->3->4->5->NULL
Wyjście : Lista połączona powinna zostać zmieniona na,
5->4->3->2->1->NULLjdbcWejście : ZERO
Wyjście : ZERO
Wejście : 1->BEZ
Wyjście : 1->BEZint Java w ciągu
Odwróć połączoną listę metodą iteracyjną:
Pomysł polega na użyciu trzech wskaźników bieżąca , poprzedni, I Następny aby śledzić węzły i aktualizować łącza zwrotne.
Aby rozwiązać problem, wykonaj poniższe czynności:
- Zainicjuj trzy wskaźniki poprzednie jako NULL, bieżąca Jak głowa , I Następny jako NULL.
- Iteruj po połączonej liście. W pętli wykonaj następujące czynności:
- Przed zmianą Następny z bieżąca , przechowuj Następny węzeł
- następny = bieżący -> następny
- Teraz zaktualizuj Następny wskaźnik bieżąca do poprzednie
- curr -> następny = poprzedni
- Aktualizacja poprzednie Jak bieżąca I bieżąca Jak Następny
- poprzedni = bieżący
- curr = następny
- Przed zmianą Następny z bieżąca , przechowuj Następny węzeł
Poniżej implementacja powyższego podejścia:
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->dane = dane; następny = NULL; } }; struktura LinkedList { Głowa węzła*; LinkedList() { głowa = NULL; } /* Funkcja odwracająca połączoną listę */ void Reverse() { // Inicjowanie wskaźników bieżącego, poprzedniego i następnego Węzeł* current = head; Węzeł *prev = NULL, *next = NULL; while (current != NULL) { // Zapisz następny next = current->next; // Odwróć wskaźnik bieżącego węzła current->next = prev; // Przesuń wskaźniki o jedną pozycję do przodu. poprzedni = bieżący; bieżący = następny; } głowa = poprzednia; } /* Funkcja drukująca listę połączoną */ void print() { struct Node* temp = head; podczas gdy (temp != NULL) { cout<< temp->dane<< ' '; temp = temp->Następny; } } void push(int dane) { Węzeł* temp = nowy Węzeł(dane); temp->next = głowa; głowa = temperatura; } }; /* Kod sterownika*/ int main() { /* Rozpocznij od pustej listy */ 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->Następny; // Odwróć wskaźnik bieżącego węzła current->next = prev; // Przesuń wskaźniki o jedną pozycję do przodu. poprzedni = bieżący; bieżący = następny; } *head_ref = poprzedni; } /* Funkcja przekazująca węzeł */ void push(struct Node** head_ref, int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); nowy_węzeł->dane = nowe_dane; new_node->next = (*head_ref); (*head_ref) = nowy_węzeł; } /* Funkcja drukująca listę połączoną */ void printList(węzeł struktury* head) { węzeł struktury* temp = head; while (temp != NULL) { printf('%d ', temp->dane); temp = temp->następny; } } /* Kod sterownika*/ int main() { /* Rozpocznij od pustej listy */ struct Node* head = NULL; push(&głowa, 20); push(&głowa, 4); push(&głowa, 15); push(&głowa, 85); printf('Podana lista połączona
'); printList(głowa); wstecz(&głowa); printf('
Odwrócona lista połączona
'); printList(głowa); getchar(); }> Jawa // 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> Pyton # 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 >
Wyjście
Given linked list 85 15 4 20 Reversed linked list 20 4 15 85>
Złożoność czasowa: O(N), Przechodzenie przez połączoną listę rozmiaru N.
Przestrzeń pomocnicza: O(1)
Odwróć połączoną listę za pomocą rekurencji:
Pomysł polega na dotarciu do ostatniego węzła połączonej listy za pomocą rekurencji, a następnie rozpoczęciu odwracania połączonej listy.
obraz przeceny
Aby rozwiązać problem, wykonaj poniższe czynności:
- Podziel listę na dwie części – pierwszy węzeł i resztę połączonej listy.
- Zadzwoń do tyłu, aby zobaczyć resztę połączonej listy.
- Najpierw połącz resztę połączonej listy.
- Napraw wskaźnik głowy na NULL
Poniżej znajduje się implementacja powyższego podejścia:
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->dane = dane; następny = NULL; } }; struktura LinkedList { Głowa węzła*; LinkedList() { głowa = NULL; } Node* Reverse(Node* head) /* Funkcja drukująca listę połączoną */ void print() { struct Node* temp = head; podczas gdy (temp != NULL) { cout<< temp->dane<< ' '; temp = temp->Następny; } } void push(int dane) { Węzeł* temp = nowy Węzeł(dane); temp->next = głowa; głowa = temperatura; } }; /* Program sterownika do testowania powyższej funkcji*/ int main() { /* Zacznij od pustej listy */ 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; }> Jawa // 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> Pyton '''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 >
Wyjście
Given linked list 85 15 4 20 Reversed linked list 20 4 15 85>
Złożoność czasowa: O(N), Jednorazowe odwiedzanie każdego węzła
Przestrzeń pomocnicza: O(N), przestrzeń stosu wywołań funkcji
Odwróć połączoną listę za pomocą metody rekurencyjnej ogona:
Założeniem jest utrzymanie trzech wskaźników poprzedni , aktualny I Następny , rekurencyjnie odwiedzaj każdy węzeł i twórz łącza za pomocą tych trzech wskaźników.
sterta i sortowanie po stercie
Aby rozwiązać problem, wykonaj poniższe czynności:
- Pierwsza aktualizacja, następnie następny węzeł prądu, tj. następny = bieżący->następny
- Teraz utwórz łącze odwrotne z bieżącego węzła do poprzedniego węzła, tj. curr->next = prev
- Jeśli odwiedzany węzeł jest ostatnim węzłem, po prostu wykonaj łącze odwrotne z bieżącego węzła do poprzedniego węzła i zaktualizuj nagłówek.
Poniżej implementacja powyższego podejścia:
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->następny) { *głowa = prąd; /* Aktualizacja obok poprzedniego węzła */ curr->next = prev; powrót; } /* Zapisz curr->next węzeł dla wywołania rekurencyjnego */ Node* next = curr->next; /* i zaktualizuj następny ..*/ curr->next = prev; ReverseUtil(next, curr, head); } // Funkcja narzędziowa umożliwiająca wydrukowanie połączonej listy void printlist(Node* head) { while (head != NULL) { cout<< head->dane<< ' '; head = head->Następny; } cout<< endl; } // Driver code int main() { Node* head1 = new Node(1); head1->następny = nowy węzeł(2); head1->next->next = nowy węzeł(3); head1->next->next->next = nowy węzeł(4); head1->next->next->next->next = nowy węzeł(5); head1->next->next->next->next->next = nowy Node(6); head1->next->next->next->next->next->next = nowy Node(7); head1->następny->następny->następny->następny->następny->następny->następny = nowy 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->następny) { *głowa = prąd; /* Aktualizacja obok poprzedniego węzła */ curr->next = prev; powrót; } /* Zapisz curr->next węzeł dla wywołania rekurencyjnego */ Node* next = curr->next; /* i zaktualizuj następny ..*/ curr->next = prev; ReverseUtil(next, curr, head); } // Funkcja narzędziowa do tworzenia nowego węzła Node* newNode(int key) { Node* temp = (Node*)malloc(sizeof(Node)); temp->dane = klucz; temp->dalej = NULL; temperatura powrotu; } // Funkcja narzędziowa umożliwiająca wydrukowanie połączonej listy void printlist(Node* head) { while (head != NULL) { printf('%d ', head->data); głowa = głowa->następny; } printf('
'); } // Kod sterownika int main() { Węzeł* head1 = newNode(1); head1->next = nowyWęzeł(2); head1->next->next = newNode(3); head1->next->next->next = newNode(4); head1->next->next->next->next = newNode(5); head1->następny->następny->następny->następny->następny = newNode(6); head1->następny->następny->następny->następny->następny->następny = newNode(7); head1->następny->następny->następny->następny->następny->następny->następny = newNode(8); printf('Podana lista połączona
'); lista wydruku(głowa1); wstecz(&głowa1); printf('Odwrócona lista połączona
'); lista wydruku(głowa1); zwróć 0; } // Ten kod został napisany przez Adityę Kumar (adityakumar129)> Jawa // 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->następny węzeł dla wywołania rekurencyjnego */ Węzeł następny1 = curr.next; /* i zaktualizuj dalej ..*/ curr.next = prev; ReverseUtil(next1, curr); powrót głowy; } // drukuje zawartość podwójnie połączonej listy void printList(Node node) { while (node != null) { System.out.print(node.data + ' '); węzeł = węzeł. następny; } } // Kod sterownika public static void main(String[] args) { Lista LinkedList = nowa Lista LinkedList(); list.head = nowy węzeł(1); list.head.next = nowy węzeł(2); list.head.next.next = nowy węzeł(3); list.head.next.next.next = nowy węzeł(4); list.head.next.next.next.next = nowy węzeł(5); list.head.next.next.next.next.next = nowy węzeł(6); list.head.next.next.next.next.next.next = nowy węzeł(7); list.head.next.next.next.next.next.next.next = nowy węzeł(8); System.out.println('Podana lista połączona '); lista.printList(głowa); Węzeł res = list.reverseUtil(head, null); System.out.println('
Odwrócona lista połączona '); lista.printList(res); } } // Ten kod został napisany przez Adityę Kumar (adityakumar129)> Pyton # 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->następny węzeł dla wywołania rekurencyjnego */ Węzeł następny1 = curr.next; /* i zaktualizuj dalej ..*/ curr.next = prev; ReverseUtil(next1, curr); powrót głowy; } // drukuje zawartość podwójnie połączonej listy void printList(węzeł węzła) { while (węzeł != null) { Console.Write(node.data + ' '); węzeł = węzeł. następny; } } // Kod sterownika public static void Main(String[] args) { LinkedList list = new LinkedList(); list.head = nowy węzeł(1); list.head.next = nowy węzeł(2); list.head.next.next = nowy węzeł(3); list.head.next.next.next = nowy węzeł(4); list.head.next.next.next.next = nowy węzeł(5); list.head.next.next.next.next.next = nowy węzeł(6); list.head.next.next.next.next.next.next = nowy węzeł(7); list.head.next.next.next.next.next.next.next = nowy węzeł(8); Console.WriteLine('Podana lista połączona '); lista.printList(list.head); Węzeł res = list.reverseUtil(list.head, null); Console.WriteLine('
Odwrócona lista połączona '); lista.printList(res); } } // Ten kod został napisany przez Rajput-Ji> JavaScript >
Wyjście
Given linked list 1 2 3 4 5 6 7 8 Reversed linked list 8 7 6 5 4 3 2 1>
Złożoność czasowa: O(N), odwiedzanie każdego węzła połączonej listy o rozmiarze N.
Przestrzeń pomocnicza: O(N), przestrzeń stosu wywołań funkcji
Odwróć połączoną listę za pomocą Pomysł jest taki, aby przechowywać wszystkie węzły na stosie, a następnie utworzyć listę z odwrotnymi linkami.
Aby rozwiązać problem, wykonaj poniższe czynności:
- Przechowuj węzły (wartości i adres) na stosie, aż zostaną wprowadzone wszystkie wartości.
- Po zakończeniu wszystkich wpisów zaktualizuj wskaźnik Head do ostatniej lokalizacji (tj. ostatniej wartości).
- Zacznij wyświetlać węzły (wartość i adres) i przechowuj je w tej samej kolejności, aż stos będzie pusty.
- Zaktualizuj następny wskaźnik ostatniego węzła na stosie o wartość NULL.
Poniżej implementacja powyższego podejścia:
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; Węzeł* temp = *głowa; while (temp->next != NULL) { // Włóż wszystkie węzły, aby utworzyć stos s.push(temp); temp = temp->następny; } *głowa = temperatura; while (!s.empty()) { // Przechowuje najwyższą wartość stosu na liście temp->next = s.top(); // Pobiera wartość ze stosu s.pop(); // zaktualizuj następny wskaźnik na liście temp = temp->next; } temp->next = NULL; } // Funkcja wyświetlająca elementy listy void printlist(Node* temp) { while (temp != NULL) { cout<< temp->dane<< ' '; temp = temp->Następny; } } // Program wstawiający tył połączonej listy void wstaw_back(Node** head, int value) { // użyliśmy metody wstawiania na końcu, aby wprowadzić wartości // na listę.(np.: head->1->2->3->4->Null) Węzeł* temp = nowy Węzeł(wartość); temp->dalej = NULL; // Jeśli *head równa się NULL if (*head == NULL) { *head = temp; powrót; } else { Węzeł* last_node = *głowa; while (last_node->next != NULL) last_node = last_node->next; last_node->next = temp; powrót; } } // Kod sterownika int main() { Węzeł* head = NULL; wstaw_back(&głowa, 1); wstaw_back(&głowa, 2); wstaw_back(&głowa, 3); wstaw_back(&głowa, 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)> Jawa // 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 = nowy stos(); Temperatura węzła = głowa; while (temp.next != null) { // Włóż wszystkie węzły do stosu s.add(temp); temp = temp.następny; } głowa = temperatura; while (!s.isEmpty()) { // Zapisz najwyższą wartość stosu na liście temp.next = s.peek(); // Pobiera wartość ze stosu s.pop(); // zaktualizuj następny wskaźnik na liście temp = temp.next; } temp.next = null; } // Funkcja wyświetlająca elementy listy static void printlist(Node temp) { while (temp != null) { System.out.print(temp.data + ' '); temp = temp.następny; } } // Program wstawiający tył połączonej listy static void wstaw_back(int wartość) { // użyliśmy metody wstawiania na końcu, aby wprowadzić // wartości na listę.(np.: head.1.2.3.4.Null) Węzeł temp = nowy węzeł (wartość); temp.next = null; // Jeśli *head równa się null if (head == null) { head = temp; powrót; } else { Węzeł last_node = głowa; while (last_node.next != null) last_node = last_node.next; last_node.next = temp; powrót; } } // Kod sterownika public static void main(String[] args) { wstaw_back(1); wstaw_powrót(2); wstaw_powrót(3); wstaw_powrót(4); System.out.print('Podana lista połączona
'); lista wydruku(głowa); odwróćLL(); System.out.print('
Odwrócona lista połączona
'); lista wydruku(głowa); } } // Ten kod został napisany przez Adityę Kumar (adityakumar129)> Pyton # 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 = Brak zwraca głowicę # Kod sterownika if __name__ == '__main__': head = ListNode(1, ListNode(2, ListNode(3, ListNode(4)))) print('Podana lista połączona') temp = głowa póki temp: print(temp.val, end=' ') temp = temp.next obj = Solution() print('
Odwrócona lista połączona') head = obj.reverseLLUsingStack(head) while 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 = nowy stos(); Temperatura węzła = głowa; while (temp.next != null) { // Włóż wszystkie węzły // do stosu s.Push(temp); temp = temp.następny; } głowa = temperatura; while (s.Count != 0) { // Zapisz najwyższą wartość // stosu na liście temp.next = s.Peek(); // Pobiera wartość ze stosu s.Pop(); // Zaktualizuj następny wskaźnik w // liście temp = temp.next; } temp.next = null; } // Funkcja wyświetlająca // elementy listy static void printlist(Node temp) { while (temp != null) { Console.Write(temp.data + ' '); temp = temp.następny; } } // Funkcja wstawiania z tyłu // połączonej listy static void wstawka_back(int val) { // Użyliśmy metody wstawiania z tyłu // do wprowadzania wartości na listę.(np.: // head.1.2.3.4 .Null) Temp. węzła = nowy węzeł(val); temp.next = null; // Jeśli *head równa się null if (head == null) { head = temp; powrót; } else { Węzeł last_node = głowa; while (last_node.next != null) { last_node = last_node.next; } last_node.next = temp; powrót; } } // Kod sterownika public static void Main(String[] args) { wstaw_back(1); wstaw_powrót(2); wstaw_powrót(3); wstaw_powrót(4); Console.Write('Podana lista połączona
'); lista wydruku(głowa); odwróćLL(); Console.Write('
Odwrócona lista połączona
'); lista wydruku(głowa); } } // Ten kod został stworzony przez gauravrajput1> JavaScript >
Wyjście
Given linked list 1 2 3 4 Reversed linked list 4 3 2 1>
Złożoność czasowa: O(N), odwiedzanie każdego węzła połączonej listy o rozmiarze N.
Przestrzeń pomocnicza: O(N), Spacja służy do przechowywania węzłów na stosie.