92. 反转链表 II
解题思路:
从m到n的位置反转链表,利用头插法可以反转排列的特性进行
- 首先要定义两个头节点 s_head和new_head ,定义头节点的目的是为了方便统一处理,否则会很麻烦
- 定义index = 0 为当前指针索引位置,如果处于m的位置上,则要记录反转链表的新尾巴
- 如果处于m和n之间,则利用头插法,把当前节点插入新链表中
- 如果处于n的位置上,则要把新链表重新插回原来的链表中
源代码:
/**
* 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) {
if(m == n) return head;
ListNode *s_head = new ListNode(-1);
s_head->next = head;
ListNode *last = head, *new_head = new ListNode(-1), *root = s_head, *tmp, *tmp_last;
new_head->next = NULL;
int index = 0;
while(root){
tmp = root->next;
if(index == m-1) last = root;
if(index >= m && index <= n){
root->next = new_head->next;
new_head->next = root;
if(index == m) tmp_last = root;
if(index == n){
tmp_last->next = tmp;
last->next = new_head->next;
return s_head->next;
}
}
root = tmp;
index ++;
}
return s_head->next;;
}
};