题解 | #牛群的重新排列#
牛群的重新排列
https://www.nowcoder.com/practice/5183605e4ef147a5a1639ceedd447838
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param left int整型
* @param right int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int left, int right)
{
// write code here
vector<int> data;
while(head != NULL)
{
data.push_back(head->val);
head = head->next;
}
int a = left - 1;
int b = right - 1;
while(a <= b)
{
swap(data[a],data[b]);
a++;
b--;
}
ListNode* prev = new ListNode(0);
ListNode* result = prev;
for (auto it : data)
{
ListNode* cur = new ListNode(it);
prev->next = cur;
prev = cur;
}
return result->next;
}
};
