假设我们有一个链表。我们必须将节点从位置m反转到n。我们必须一次性完成。因此,如果列表为[1,2,3,4,5]且m = 2和n = 4,则结果将为[1,4,,3,2,5]
让我们看看步骤-
将有两种方法,reverseN()和reverseBetween()。reverseBetween()将用作主要方法。
将一个称为后继的链接节点指针定义为null
reverseN的工作方式如下:
如果n = 1,则后继者==首位,然后返回head
最后=反向N(头部的下一个,n-1)
下一首(下首)=首,首首下一个:=后继,返回最后一个
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, ]