题解 | #牛群的重新排列#
牛群的重新排列
https://www.nowcoder.com/practice/5183605e4ef147a5a1639ceedd447838
知识点:
链表/反转
分析:
1.设置一个dummy节点, g指向dummy,p指向dummy的next
2.先将两个指针往后移动left个
3.然后开始遍历区间长度right-left进行反转
编程语言:
C++
完整代码:
ListNode* reverseBetween(ListNode* head, int left, int right) { //先设置一个dummy结点 ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* g = dummy; //双指针 1. 指向dummy ListNode* p = dummy->next; //双指针 2.指向dummy的下一个 for(int i = 0;i< left - 1;i++){ //同时向后移动left个 p = p->next; g = g->next; } for(int i= 0; i<right - left;++i){ //然后遍历这个区间段内的长度 ListNode* tmp = p->next; p->next = p->next->next; tmp->next = g->next; g->next = tmp; } return dummy->next; }