C++刷LeetCode(92. 反转链表 II)【翻转链表】
题目描述:反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* res = new ListNode(-1);//关键点,至少保证四个长度
res -> next = head;
ListNode* temp1 = res;
int count = m - 1;
while(count > 0){
temp1 = temp1 -> next;
count--;
}
ListNode* temp2 = temp1 -> next;
ListNode* temp3 = temp2 -> next;
int gap = n - m;
while(gap > 0){
gap--;
ListNode* temp = temp3 -> next;
temp3 -> next = temp2;
temp2 = temp3;
temp3 = temp;
}
ListNode* temp4 = temp1 -> next;
temp1 -> next = temp2;
temp4 -> next = temp3;
return res -> next;
}
};
页:
[1]