链表的就地逆置我们讲解过了,接下来,关于单链表的中间段逆置,是一个稍有难度的问题。问题描述如下:
给定start和end,逆置从start到end的所有节点。
思路:这里需要定位逆置段开始节点,逆置段前驱结点,逆置段结束节点,以及逆置段结束节点后继。
定位好了之后,再对逆置段截断、做连接即可。
具体代码如下:
// 链表的中间段就地逆序
ListNode* inverse_between_list(ListNode* head, int start, int end) {
int exchange_length = end - start + 1;
ListNode* result = head; // 最终返回的结果指针
ListNode* pre_head = NULL; // 逆置节点的前驱指针
while (head && --start) {
pre_head = head;
head = head->next;
}
ListNode* modify_tail = head;
ListNode* new_head = null; // 将开始逆置段做截断
while (head && exchange_length) {
ListNode* tmp_ptr = head->next;
head->next = new_head;
new_head = head;
head = tmp_ptr;
exchange_length --;
}
modify_tail->next = head; // 断层连接
if (pre_head) {
// 如果pre_head非空,即并非从头开始逆置,即start不等于1
pre_head->next = new_head;
} else {
// 否则,就是从头开始逆置
result = new_head;
}
return result;
}