logo

Скасування пов’язаного списку

Маючи вказівник на головний вузол зв’язаного списку, завдання полягає в тому, щоб перевернути зв’язаний список. Нам потрібно перевернути список, змінивши зв’язки між вузлами.

Приклади :



Введення : Голова наступного пов’язаного списку
1->2->3->4->NULL
Вихід : пов’язаний список слід змінити на
4->3->2->1->NULL

Введення : Голова наступного пов’язаного списку
1->2->3->4->5->NULL
Вихід : пов’язаний список слід змінити на
5->4->3->2->1->NULL

Введення : НУЛЬ
Вихід : НУЛЬ



Введення : 1->NULL
Вихід : 1->NULL

Рекомендована практика Перевернути пов’язаний список Спробуйте!

Перевернути пов’язаний список за допомогою ітераційного методу:

Ідея полягає у використанні трьох вказівників curr , попередній, і наступний для відстеження вузлів для оновлення зворотних посилань.

Щоб вирішити проблему, виконайте наведені нижче дії.



  • Ініціалізація трьох покажчиків поперед як NULL, curr як голова , і наступний як NULL.
  • Ітерація пов’язаного списку. У циклі виконайте такі дії:
    • Перед зміною наступний з curr , зберігати наступний вузол
      • наступний = поточний -> наступний
    • Тепер оновіть наступний покажчик curr до поперед
      • поточний -> наступний = попередній
    • оновлення поперед як curr і curr як наступний
      • попередній = поточний
      • curr = наступний

Нижче наведено реалізацію вищезазначеного підходу:

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->дані = дані;  наступний = NULL;  } }; struct LinkedList { Node* head;  LinkedList() { head = NULL; } /* Функція перевертання пов’язаного списку */ void reverse() { // Ініціалізація поточного, попереднього та наступного вказівників Node* current = head;  Вузол *prev = NULL, *next = NULL;  while (current != NULL) { // Зберегти next next = current->next;  // Зворотний покажчик поточного вузла current->next = prev;  // Перемістити покажчики на одну позицію вперед.  попередній = поточний;  поточний = наступний;  } голова = попередній;  } /* Функція друку пов’язаного списку */ void print() { struct Node* temp = head;  while (temp != NULL) { cout<< temp->даних<< ' ';  temp = temp->наступний;  } } void push(int data) { Node* temp = new Node(data);  temp->next = голова;  голова = темп;  } }; /* Код драйвера*/ int main() { /* Почати з порожнього списку */ 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->наступний;  // Зворотний покажчик поточного вузла current->next = prev;  // Перемістити покажчики на одну позицію вперед.  попередній = поточний;  поточний = наступний;  } *head_ref = попередній; } /* Функція для надсилання вузла */ void push(struct Node** head_ref, int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));  новий_вузол->дані = нові_дані;  новий_вузол->наступний = (*head_ref);  (*head_ref) = новий_вузол; } /* Функція друку пов’язаного списку */ void printList(struct Node* head) { struct Node* temp = head;  while (temp != NULL) { printf('%d ', temp->data);  temp = temp->next;  } } /* Код драйвера*/ int main() { /* Почати з порожнього списку */ struct Node* head = NULL;  push(&head, 20);  push(&head, 4);  push(&head, 15);  push(&head, 85);  printf('Заданий пов'язаний список
');  printList(голова);  реверс(&голова);  printf('
Обернений пов'язаний список 
');  printList(голова);  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>
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
>

Вихід
Given linked list 85 15 4 20 Reversed linked list 20 4 15 85>

Часова складність: O(N), перехід по пов’язаному списку розміру N.
Допоміжний простір: О(1)

Перевернути пов’язаний список за допомогою рекурсії:

Ідея полягає в тому, щоб досягти останнього вузла пов’язаного списку за допомогою рекурсії, а потім почати обертати зв’язаний список.

Щоб вирішити проблему, виконайте наведені нижче дії.

  • Розділіть список на дві частини – перший вузол і решту пов’язаного списку.
  • Зворотний виклик для решти пов’язаного списку.
  • Пов’яжіть решту пов’язаного списку з першим.
  • Виправте вказівник голови на NULL

Нижче наведено реалізацію вищезазначеного підходу:

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->дані = дані;  наступний = NULL;  } }; struct LinkedList { Node* head;  LinkedList() { head = NULL; } Node* reverse(Node* head) /* Функція друку пов’язаного списку */ void print() { struct Node* temp = head;  while (temp != NULL) { cout<< temp->даних<< ' ';  temp = temp->наступний;  } } void push(int data) { Node* temp = new Node(data);  temp->next = голова;  голова = темп;  } }; /* Програма драйвера для перевірки вищевказаної функції*/ int main() { /* Почати з порожнього списку */ 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
>

Вихід
Given linked list 85 15 4 20 Reversed linked list 20 4 15 85>

Часова складність: O(N), відвідування кожного вузла один раз
Допоміжний простір: O(N), простір у стеку викликів функцій

Перевернути пов’язаний список за допомогою хвостового рекурсивного методу:

Ідея полягає в тому, щоб зберегти три покажчики Попередній , поточний і наступний , рекурсивно відвідувати кожен вузол і створювати посилання за допомогою цих трьох вказівників.

Щоб вирішити проблему, виконайте наведені нижче дії.

  • Спочатку оновіть наступний вузол поточного i.e. наступний = поточний-> наступний
  • Тепер створіть зворотне посилання від поточного вузла до попереднього вузла, тобто curr->next = prev
  • Якщо відвіданий вузол є останнім вузлом, тоді просто створіть зворотне посилання від поточного вузла до попереднього вузла та оновіть голову.

Нижче наведено реалізацію вищезазначеного підходу:

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->наступний) { *head = curr;  /* Оновлення поруч із попереднім вузлом */ curr->next = prev;  повернення;  } /* Зберегти curr->next вузол для рекурсивного виклику */ Node* next = curr->next;  /* і оновити далі ..*/ curr->next = prev;  reverseUtil(наступний, curr, голова); } // Допоміжна функція для друку пов’язаного списку void printlist(Node* head) { while (head != NULL) { cout<< head->даних<< ' ';  head = head->наступний;  } cout<< endl; } // Driver code int main() {  Node* head1 = new Node(1);  head1->наступний = новий вузол (2);  head1->next->next = новий вузол(3);  head1->next->next->next = новий вузол(4);  head1->next->next->next->next = новий вузол(5);  голова1->наступний->наступний->наступний->наступний->наступний = новий вузол(6);  head1->наступний->наступний->наступний->наступний->наступний->наступний = новий вузол(7);  head1->наступний->наступний->наступний->наступний->наступний->наступний->наступний = новий вузол(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->наступний) { *head = curr;  /* Оновлення поруч із попереднім вузлом */ curr->next = prev;  повернення;  } /* Зберегти curr->next вузол для рекурсивного виклику */ Node* next = curr->next;  /* і оновити далі ..*/ curr->next = prev;  reverseUtil(наступний, curr, голова); } // Допоміжна функція для створення нового вузла Node* newNode(int key) { Node* temp = (Node*)malloc(sizeof(Node));  temp->data = ключ;  temp->next = NULL;  зворотна температура; } // Допоміжна функція для друку пов’язаного списку void printlist(Node* head) { while (head != NULL) { printf('%d ', head->data);  голова = голова->наступний;  } printf('
'); } // Код драйвера int main() { Node* head1 = newNode(1);  head1->next = newNode(2);  head1->next->next = newNode(3);  head1->next->next->next = newNode(4);  head1->next->next->next->next = newNode(5);  head1->наступний->наступний->наступний->наступний->наступний = newNode(6);  head1->наступний->наступний->наступний->наступний->наступний->наступний = newNode(7);  head1->наступний->наступний->наступний->наступний->наступний->наступний->наступний = newNode(8);  printf('Заданий пов'язаний список
');  список друку (head1);  реверс(&head1);  printf('Обернений пов'язаний список
');  список друку (head1);  повернути 0; } // Цей код створено 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->наступний вузол для рекурсивного виклику */ Вузол next1 = curr.next;  /* і оновити далі ..*/ curr.next = prev;  reverseUtil(наступний1, curr);  поворотна головка;  } // друкує вміст подвійного зв’язаного списку void printList(Node node) { while (node ​​!= null) { System.out.print(node.data + ' ');  node = node.next;  } } // Код драйвера public static void main(String[] args) { LinkedList list = new LinkedList();  list.head = новий вузол (1);  list.head.next = новий вузол (2);  list.head.next.next = новий вузол (3);  list.head.next.next.next = новий вузол (4);  list.head.next.next.next.next = новий вузол (5);  list.head.next.next.next.next.next = новий вузол (6);  list.head.next.next.next.next.next.next = новий вузол (7);  list.head.next.next.next.next.next.next.next = новий вузол(8);  System.out.println('Заданий пов'язаний список ');  list.printList(head);  Node res = list.reverseUtil(head, null);  System.out.println('
Зворотний пов'язаний список ');  list.printList(res);  } } // Цей код створено Aditya Kumar (adityakumar129)>
Python
# 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->наступний вузол для рекурсивного виклику */ Вузол next1 = curr.next;  /* і оновити далі ..*/ curr.next = prev;  reverseUtil(наступний1, curr);  поворотна головка;  } // друкує вміст подвійного зв’язаного списку void printList(Node node) { while (node ​​!= null) { Console.Write(node.data + ' ');  node = node.next;  } } // Код драйвера public static void Main(String[] args) { LinkedList list = new LinkedList();  list.head = новий вузол (1);  list.head.next = новий вузол (2);  list.head.next.next = новий вузол (3);  list.head.next.next.next = новий вузол (4);  list.head.next.next.next.next = новий вузол (5);  list.head.next.next.next.next.next = новий вузол (6);  list.head.next.next.next.next.next.next = новий вузол (7);  list.head.next.next.next.next.next.next.next = новий вузол(8);  Console.WriteLine('Заданий пов'язаний список ');  list.printList(list.head);  Node res = list.reverseUtil(list.head, null);  Console.WriteLine('
Обернений пов'язаний список ');  list.printList(res);  } } // Цей код надав Rajput-Ji>
Javascript
>

Вихід
Given linked list 1 2 3 4 5 6 7 8 Reversed linked list 8 7 6 5 4 3 2 1>

Часова складність: O(N), відвідування кожного вузла пов’язаного списку розміром N.
Допоміжний простір: O(N), простір у стеку викликів функцій

Перевернути пов’язаний список за допомогою Ідея полягає в тому, щоб зберегти всі вузли в стеку, а потім створити зворотний зв’язаний список.

Щоб вирішити проблему, виконайте наведені нижче дії.

  • Зберігайте вузли (значення та адресу) у стеку, доки не буде введено всі значення.
  • Після того, як усі записи буде зроблено, оновіть покажчик Head до останнього місця (тобто останнього значення).
  • Почніть витягувати вузли (значення та адресу) і зберігати їх у тому самому порядку, доки стек не буде порожнім.
  • Оновіть наступний покажчик останнього вузла в стеку на NULL.

Нижче наведено реалізацію вищезазначеного підходу:

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 = *head;  while (temp->next != NULL) { // Вставте всі вузли в стек s.push(temp);  temp = temp->next;  } *head = temp;  while (!s.empty()) { // Збереження верхнього значення стека в списку temp->next = s.top();  // Витягуємо значення зі стеку s.pop();  // оновити наступний покажчик у списку temp = temp->next;  } temp->next = NULL; } // Функція для відображення елементів у списку void printlist(Node* temp) { while (temp != NULL) { cout<< temp->даних<< ' ';  temp = temp->наступний;  } } // Програма для вставлення назад пов’язаного списку void insert_back(Node** head, int value) { // ми використали метод вставки at back для введення значень // у список. (наприклад: head->1->2->3->4->Null) Node* temp = новий вузол(значення);  temp->next = NULL;  // Якщо *head дорівнює NULL if (*head == NULL) { *head = temp;  повернення;  } else { Node* last_node = *head;  while (останній_вузол->наступний != NULL) останній_вузол = останній_вузол->наступний;  останній_вузол->наступний = тимчасовий;  повернення;  } } // Код драйвера int main() { Node* head = NULL;  вставити_назад(&голова, 1);  вставити_назад(&голова, 2);  вставити_назад(&голова, 3);  вставити_назад(&голова, 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 = новий стек();  Температура вузла = голова;  while (temp.next != null) { // Вставити всі вузли в стек s.add(temp);  temp = temp.next;  } голова = темп;  while (!s.isEmpty()) { // Збереження верхнього значення стека в списку temp.next = s.peek();  // Витягуємо значення зі стеку s.pop();  // оновити наступний покажчик у списку temp = temp.next;  } temp.next = null;  } // Функція для відображення елементів у списку static void printlist(Node temp) { while (temp != null) { System.out.print(temp.data + ' ');  temp = temp.next;  } } // Програма для вставлення назад зв’язаного списку static void insert_back(int value) { // ми використали метод insertion at back для введення // значень у список. (наприклад: head.1.2.3.4.Null) Node temp = новий вузол (значення);  temp.next = null;  // Якщо *head дорівнює null if (head == null) { head = temp;  повернення;  } else { Node last_node = head;  while (last_node.next != null) last_node = last_node.next;  last_node.next = temp;  повернення;  } } // Код драйвера public static void main(String[] args) { insert_back(1);  вставити назад(2);  вставити_назад(3);  вставити назад(4);  System.out.print('Заданий пов'язаний список
');  список друку (голова);  reverseLL();  System.out.print('
Зворотний пов'язаний список
');  список друку (голова);  } } // Цей код створено Aditya Kumar (adityakumar129)>
Python
# 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 = Немає return head # Код драйвера if __name__ == '__main__': head = ListNode(1, ListNode(2, ListNode(3, ListNode(4)))) print('Заданий пов'язаний список') temp = head while temp: print(temp.val, end=' ') temp = temp.next obj = Solution() print(' 
Обернутий зв'язаний список') 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 = новий стек();  Температура вузла = голова;  while (temp.next != null) { // Вставити всі вузли // в стек s.Push(temp);  temp = temp.next;  } голова = темп;  while (s.Count != 0) { // Збереження верхнього значення // стека в списку temp.next = s.Peek();  // Витягуємо значення зі стеку s.Pop();  // Оновити вказівник next у // списку temp = temp.next;  } temp.next = null;  } // Функція для відображення // елементів у списку static void printlist(Node temp) { while (temp != null) { Console.Write(temp.data + ' ');  temp = temp.next;  } } // Функція для вставки назад у // зв’язаний список static void insert_back(int val) { // Ми використали метод вставки назад // для введення значень у список. (наприклад: // head.1.2.3.4 .Null) Node temp = новий вузол (val);  temp.next = null;  // Якщо *head дорівнює null if (head == null) { head = temp;  повернення;  } else { Node last_node = head;  while (last_node.next != null) { last_node = last_node.next;  } last_node.next = temp;  повернення;  } } // Код драйвера public static void Main(String[] args) { insert_back(1);  вставити назад(2);  вставити_назад(3);  вставити назад(4);  Console.Write('Заданий пов'язаний список
');  список друку (голова);  reverseLL();  Console.Write('
Обернутий пов'язаний список
');  список друку (голова);  } } // Цей код створено gauravrajput1>
Javascript
>

Вихід
Given linked list 1 2 3 4 Reversed linked list 4 3 2 1>

Часова складність: O(N), відвідування кожного вузла пов’язаного списку розміром N.
Допоміжний простір: O(N), простір використовується для зберігання вузлів у стеку.