题目描述
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
参考代码
常规题,“多指针”,别断链就好。(总共用了2 + 3 == 5个指针)
/**
* 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 == nullptr)
return nullptr;
ListNode* dummyHead = new ListNode(-1); // 很好用!
dummyHead->next = head;
ListNode* pFront = dummyHead;
ListNode* pNode = head;
for(int i = 0; i < m-1; i++){
pFront = pNode;
if(pNode != nullptr)
pNode = pNode->next;
}
ListNode* pPre = nullptr;
int cnt = n - m + 1;
while(pNode && cnt--){
ListNode* pNext = pNode->next;
pNode->next = pPre;
pPre = pNode;
pNode = pNext;
if(cnt == 0){
pFront->next->next = pNode;
pFront->next = pPre;
}
}
return dummyHead->next;
}
};