在 C++ 中反轉連結串列 II\n


假設我們有一個連結串列。我們必須反轉從 m 到 n 位置的節點。我們必須一次性完成。因此,如果連結串列是 [1,2,3,4,5] 且 m = 2 和 n = 4,則結果將是 [1,4,3,2,5]

讓我們瞭解一下這些步驟 −

  • 將有兩種方法,reverseN() 和 reverseBetween()。reverseBetween() 將作為主方法。
  • 定義一個稱為 successor 的連結節點指標,並設其為 null
  • reverseN 的工作方式如下 −
  • 如果 n = 1,則 successor := head 的下一個,並返回 head
  • last = reverseN(head 的下一個,n - 1)
  • (head 的下一個) 的下一個 = head,head 的下一個 := successor,返回 last
  • reverseBetween() 方法將像 −
  • 如果 m = 1,則返回 reverseN(head,n)
  • head 的下一個 := reverseBetween(head 的下一個,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, ]

更新時間:2020 年 5 月 4 日

193 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告