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

권장 연습 연결된 목록을 뒤집으세요. 시도해 보세요!

반복 방법으로 연결 목록을 뒤집습니다.

아이디어는 세 개의 포인터를 사용하는 것입니다 현재 , 이전, 그리고 다음 역방향 링크를 업데이트하기 위해 노드를 추적합니다.

문제를 해결하려면 아래 단계를 따르십시오.



  • 세 개의 포인터 초기화 이전 NULL로, 현재 ~처럼 머리 , 그리고 다음 NULL로.
  • 연결된 목록을 반복합니다. 루프에서 다음을 수행합니다.
    • 변경하기 전에 다음 ~의 현재 , 저장 다음 마디
      • 다음 = 현재 -> 다음
    • 이제 업데이트하세요 다음 포인터 현재 ~로 이전
      • 현재 -> 다음 = 이전
    • 업데이트 이전 ~처럼 현재 그리고 현재 ~처럼 다음
      • 이전 = 현재
      • 현재 = 다음

다음은 위의 접근 방식을 구현한 것입니다.

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 { 노드* 헤드;  LinkedList() { 헤드 = NULL; } /* 연결 리스트를 반전시키는 함수 */ void reverse() { // 현재, 이전 및 다음 포인터 초기화 Node* current = head;  노드 *prev = NULL, *next = NULL;  while (current != NULL) { // 다음 저장 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);  온도->다음 = 헤드;  머리 = 온도;  } }; /* 드라이버 코드*/ int main() { /* 빈 목록으로 시작 */ LinkedList ll;  ll.push(20);  ll.push(4);  ll.push(15);  ll.push(85);  시합<< 'Given linked list
';  ll.print();  ll.reverse();  cout << '
Reversed linked list 
';  ll.print();  return 0; }>
// 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));  new_node->data = new_data;  new_node->next = (*head_ref);  (*head_ref) = new_node; } /* 연결 리스트를 인쇄하는 함수 */ void printList(struct Node* head) { struct Node* temp = head;  while (temp != NULL) { printf('%d ', temp->data);  온도 = 온도->다음;  } } /* 드라이버 코드*/ int main() { /* 빈 목록으로 시작 */ struct Node* head = NULL;  push(&헤드, 20);  push(&헤드, 4);  push(&헤드, 15);  push(&헤드, 85);  printf('주어진 연결리스트
');  printList(헤드);  역방향(&헤드);  printf('
역방향 연결 리스트 
');  printList(헤드);  getchar(); }>
자바
// 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 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# 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>
자바스크립트
>

산출
Given linked list 85 15 4 20 Reversed linked list 20 4 15 85>

시간 복잡도: O(N), 크기 N의 연결리스트를 탐색합니다.
보조 공간: 오(1)

재귀를 사용하여 연결 목록을 되돌립니다.

아이디어는 재귀를 사용하여 연결 목록의 마지막 노드에 도달한 다음 연결 목록을 뒤집기 시작하는 것입니다.

문제를 해결하려면 아래 단계를 따르십시오.

  • 목록을 첫 번째 노드와 나머지 연결 목록의 두 부분으로 나눕니다.
  • 연결된 목록의 나머지 부분에 대해서는 reverse를 호출합니다.
  • 나머지 연결리스트를 먼저 연결합니다.
  • 헤드 포인터를 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 { 노드* 헤드;  LinkedList() { 헤드 = 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);  온도->다음 = 헤드;  머리 = 온도;  } }; /* 위 함수를 테스트하기 위한 드라이버 프로그램*/ int main() { /* 빈 목록으로 시작 */ LinkedList ll;  ll.push(20);  ll.push(4);  ll.push(15);  ll.push(85);  시합<< 'Given linked list
';  ll.print();  ll.head = ll.reverse(ll.head);  cout << '
Reversed linked list 
';  ll.print();  return 0; }>
자바
// 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>
파이썬
'''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>
씨#
// 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>
자바스크립트
>

산출
Given linked list 85 15 4 20 Reversed linked list 20 4 15 85>

시간 복잡도: O(N), 모든 노드를 한 번씩 방문
보조 공간: O(N), 함수 호출 스택 공간

Tail Recursive 방법으로 연결된 목록을 뒤집습니다.

아이디어는 세 개의 포인터를 유지하는 것입니다 이전의 , 현재의 그리고 다음 , 모든 노드를 재귀적으로 방문하고 이 세 가지 포인터를 사용하여 링크를 만듭니다.

문제를 해결하려면 아래 단계를 따르십시오.

리눅스에서 스크립트를 실행하는 방법
  • 먼저 현재의 다음 노드로 다음을 업데이트합니다. 즉, 다음 = 현재->다음
  • 이제 현재 노드에서 이전 노드로 역방향 링크를 만듭니다. 즉, 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(다음, 현재, 선두); } // 연결 리스트를 인쇄하는 유틸리티 함수 void printlist(Node* head) { while (head != NULL) { cout<< head->데이터<< ' ';  head = head->다음;  } cout<< endl; } // Driver code int main() {  Node* head1 = new Node(1);  head1->next = 새로운 노드(2);  head1->다음->다음 = new Node(3);  head1->다음->다음->다음 = new Node(4);  head1->다음->다음->다음->다음 = new Node(5);  head1->다음->다음->다음->다음->다음 = new Node(6);  head1->다음->다음->다음->다음->다음->다음 = new Node(7);  head1->다음->다음->다음->다음->다음->다음->다음 = new Node(8);  시합<< 'Given linked list
';  printlist(head1);  reverse(&head1);  cout << 'Reversed linked list
';  printlist(head1);  return 0; }>
// 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(다음, 현재, 선두); } // 새 노드를 생성하는 유틸리티 함수 Node* newNode(int key) { Node* temp = (Node*)malloc(sizeof(Node));  임시->데이터 = 키;  임시->다음 = NULL;  복귀온도; } // 연결된 목록을 인쇄하는 유틸리티 함수 void printlist(Node* head) { while (head != NULL) { printf('%d ', head->data);  머리 = 머리->다음;  } printf('
'); } // 드라이버 코드 int main() { Node* head1 = newNode(1);  head1->next = newNode(2);  head1->다음->다음 = newNode(3);  head1->다음->다음->다음 = newNode(4);  head1->다음->다음->다음->다음 = newNode(5);  head1->다음->다음->다음->다음->다음 = newNode(6);  head1->다음->다음->다음->다음->다음->다음 = newNode(7);  head1->다음->다음->다음->다음->다음->다음->다음 = newNode(8);  printf('주어진 연결리스트
');  printlist(head1);  역방향(&head1);  printf('역방향 연결리스트
');  printlist(head1);  0을 반환합니다. } // 이 코드는 Aditya Kumar(adityakumar129)가 제공한 것입니다.>
자바
// 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->재귀 호출을 위한 다음 노드 */ Node next1 = curr.next;  /* 그리고 다음 업데이트 ..*/ curr.next = prev;  reverseUtil(next1, curr);  머리를 돌려라;  } // 이중 연결 리스트의 내용을 인쇄합니다. void printList(Node node) { while (node ​​!= null) { System.out.print(node.data + ' ');  노드 = 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);  노드 res = list.reverseUtil(head, null);  System.out.println('
역방향 연결 리스트 ');  list.printList(res);  } } // 이 코드는 Aditya Kumar(adityakumar129)가 제공한 것입니다.>
파이썬
# 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# 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->재귀 호출을 위한 다음 노드 */ Node next1 = curr.next;  /* 그리고 다음 업데이트 ..*/ curr.next = prev;  reverseUtil(next1, curr);  머리를 돌려라;  } // 이중 연결 리스트의 내용을 인쇄합니다. void printList(Node node) { while (node ​​!= null) { Console.Write(node.data + ' ');  노드 = 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);  노드 res = list.reverseUtil(list.head, null);  Console.WriteLine('
역방향 연결 리스트 ');  list.printList(res);  } } // 이 코드는 Rajput-Ji가 제공한 것입니다.>
자바스크립트
>

산출
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), 함수 호출 스택 공간

다음을 사용하여 연결 목록을 뒤집습니다. 아이디어는 스택의 모든 노드를 저장한 다음 역방향 연결 목록을 만드는 것입니다.

문제를 해결하려면 아래 단계를 따르십시오.

  • 모든 값이 입력될 때까지 노드(값 및 주소)를 스택에 저장합니다.
  • 모든 항목이 완료되면 헤드 포인터를 마지막 위치(즉, 마지막 값)로 업데이트합니다.
  • 노드(값 및 주소) 팝핑을 시작하고 스택이 빌 때까지 동일한 순서로 저장합니다.
  • 스택에 있는 마지막 노드의 다음 포인터를 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  stack에스;  노드* 온도 = *헤드;  while (temp->next != NULL) { // 모든 노드를 스택에 푸시합니다. s.push(temp);  온도 = 온도->다음;  } *머리 = 온도;  while (!s.empty()) { // 스택의 최상위 값을 리스트에 저장 temp->next = s.top();  // 스택에서 값을 팝합니다. s.pop();  // 목록의 다음 포인터를 업데이트합니다. temp = temp->next;  } 임시->다음 = NULL; } // List의 요소를 표시하는 함수 void printlist(Node* temp) { while (temp != NULL) { cout<< temp->데이터<< ' ';  temp = temp->다음;  } } // 연결 리스트의 뒤에 삽입하는 프로그램 void insert_back(Node** head, int value) { // 목록에 값을 입력하기 위해 // 삽입 메소드를 사용했습니다.(예: head->1->2->3->4->Null) 노드* 임시 = 새 노드(값);  임시->다음 = NULL;  // *head가 NULL인 경우 if (*head == NULL) { *head = temp;  반품;  } else { 노드* last_node = *head;  while (last_node->next != NULL) last_node = last_node->next;  last_node->next = 임시;  반품;  } } // 드라이버 코드 int main() { Node* head = NULL;  insert_back(&헤드, 1);  insert_back(&헤드, 2);  insert_back(&헤드, 3);  insert_back(&헤드, 4);  시합<< 'Given linked list
';  printlist(head);  reverseLL(&head);  cout << '
Reversed linked list
';  printlist(head);  return 0; } // This code is contributed by Aditya Kumar (adityakumar129)>
자바
// 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.next;  } 헤드 = 온도;  while (!s.isEmpty()) { // 스택의 최상위 값을 목록에 저장합니다. temp.next = s.peek();  // 스택에서 값을 팝합니다. s.pop();  // 목록의 다음 포인터를 업데이트합니다. temp = temp.next;  } 임시.다음 = null;  } // List의 요소를 표시하는 함수 static void printlist(Node temp) { while (temp != null) { System.out.print(temp.data + ' ');  온도 = temp.next;  } } // 연결된 목록의 뒤쪽에 삽입하는 프로그램 static void insert_back(int value) { // 목록에 값을 입력하기 위해 // 뒤쪽에 삽입 방법을 사용했습니다.(예: head.1.2.3.4.Null) Node temp = 새 노드(값);  임시.다음 = null;  // *head가 null인 경우 if (head == null) { head = temp;  반품;  } else { 노드 last_node = 헤드;  while(last_node.next != null) last_node = last_node.next;  last_node.next = 임시;  반품;  } } // 드라이버 코드 public static void main(String[] args) { insert_back(1);  insert_back(2);  insert_back(3);  insert_back(4);  System.out.print('주어진 연결 리스트
');  printlist(헤드);  역LL();  System.out.print('
역방향 연결 리스트
');  printlist(헤드);  } } // 이 코드는 Aditya Kumar(adityakumar129)가 제공한 것입니다.>
파이썬
# 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,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# 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.next;  } 헤드 = 온도;  while (s.Count != 0) { // 스택의 상위 값을 // 목록에 저장합니다. temp.next = s.Peek();  // 스택에서 값을 팝합니다. s.Pop();  // 목록의 // 다음 포인터를 업데이트합니다. temp = temp.next;  } 임시.다음 = null;  } // 표시할 함수 // List의 요소 static void printlist(Node temp) { while (temp != null) { Console.Write(temp.data + ' ');  온도 = temp.next;  } } // 연결리스트 뒤에 삽입하는 함수 // static void insert_back(int val) { // 목록에 값을 입력하기 위해 // 뒤에 삽입 메소드를 사용했습니다.(예: // head.1.2.3.4 .Null) 노드 임시 = 새 노드(val);  임시.다음 = null;  // *head가 null인 경우 if (head == null) { head = temp;  반품;  } else { 노드 last_node = 헤드;  while (last_node.next != null) { last_node = last_node.next;  } last_node.next = 임시;  반품;  } } // 드라이버 코드 public static void Main(String[] args) { insert_back(1);  insert_back(2);  insert_back(3);  insert_back(4);  Console.Write('주어진 연결 리스트
');  printlist(헤드);  역LL();  Console.Write('
역방향 연결 리스트
');  printlist(헤드);  } } // 이 코드는 gauravrajput1이 제공한 것입니다.>
자바스크립트
>

산출
Given linked list 1 2 3 4 Reversed linked list 4 3 2 1>

시간 복잡도: O(N), 크기 N인 연결리스트의 모든 노드를 방문합니다.
보조 공간: O(N), Space는 스택에 노드를 저장하는 데 사용됩니다.