题目链接:https://leetcode.com/problems/reverse-linked-list-ii/
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
思路:借助我非常喜欢的虚拟头结点,让链表走到第一个在需要交换的结点记为post(这个结点将会成为翻转区域的尾结点),并且记录post之前的一个结点记为p。找到这个点之后就可以将在范围之内的结点都插入到p的后面,直到走出需要翻转的区域,让剩下的区域链接到post后面即可。
举个栗子:
1->2->3->4->5->NULL,m = 2, n = 4
1.先让p结点走到1,2结点是第一个需要交换的结点记为post,并最终会成为交换范围的尾结点。
2.让3插入到1后面,变为1->3->2 4->5->NULL
3.让4插入到1后面,变为1->4->3->2 5->NULL
4.让剩余的链接到2后面,变为1->4->3->2->5->NULL
时间复杂度为O(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(!head) return head;
ListNode *pHead= new ListNode(0), *p =pHead, *q, *tem;
pHead->next = head;
int i = 0;
while(i++ < m-1) p = p->next;
q = p->next;
while(i++ < n)
{
tem = q->next;
q->next = tem->next;
tem->next = p->next;
p->next = tem;
}
head = pHead->next;
delete pHead;
return head;
}
};