【LeetCode】92. Reverse Linked List II(C++)
阿新 • • 發佈:2018-12-19
地址:https://leetcode.com/problems/reverse-linked-list-ii/
題目:
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
理解:
需要把連結串列的一部分翻轉。
實現:
添加了一個頭結點來處理,其中
hh
是頭結點
pre
是要反轉的部分之前的結點
pp
和pn
指向當前處理的兩個結點,pp
在左,pn
在右
pr
是翻轉後的尾節點
cnt
是需要通過pp
和pn
處理的次數
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* hh = new ListNode(0);
hh->next=head;
ListNode* pre = hh;
for (int i = 0; i < m - 1; ++i)
pre = pre->next;
ListNode* pp = pre->next;
ListNode* pr = pp;
ListNode* pn = pp->next;
int cnt = n - m;
while (cnt) {
ListNode* tmp = pn->next;
pn->next = pp;
pp = pn;
pn = tmp;
--cnt;
}
pre->next = pp;
pr->next = pn;
return hh- >next;
}
};