연결된 목록이 있다고 가정합니다. 노드를 m 위치에서 n 위치로 반전시켜야 합니다. 한 번에 완료해야 합니다. 따라서 목록이 [1,2,3,4,5]이고 m =2 및 n =4이면 결과는 [1,4,,3,2,5]
가 됩니다.단계를 살펴보겠습니다 -
- reverseN() 및 reverseBetween()의 두 가지 방법이 있습니다. reverseBetween()이 기본 메서드로 작동합니다.
- 후계자라는 하나의 링크 노드 포인터를 null로 정의
- reverseN은 다음과 같이 작동합니다 -
- n =1이면 후속 작업 :=헤드의 다음이고 헤드를 반환합니다.
- 마지막 =reverseN(머리의 다음, n - 1)
- next of (head of head) =head, and next of head :=계승자, 마지막으로 반환
- reverseBetween() 메서드는 다음과 같습니다 -
- m =1이면 reverseN(head, n)을 반환
- 머리 다음:=reverseBetween(머리의 다음, m – 1, n – 1)
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
예
#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
ListNode *head = new ListNode(v[0]);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
return head;
}
void print_list(ListNode *head){
ListNode *ptr = head;
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* successor = NULL;
ListNode* reverseN(ListNode* head, int n ){
if(n == 1){
successor = head->next;
return head;
}
ListNode* last = reverseN(head->next, n - 1);
head->next->next = head;
head->next = successor;
return last;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(m == 1){
return reverseN(head, n);
}
head->next = reverseBetween(head->next, m - 1, n - 1);
return head;
}
};
main(){
Solution ob;
vector<int> v = {1,2,3,4,5,6,7,8};
ListNode *head = make_list(v);
print_list(ob.reverseBetween(head, 2, 6));
} 입력
[1,2,3,4,5,6,7,8] 2 6
출력
[1, 6, 5, 4, 3, 2, 7, 8, ]