1. 程式人生 > >【LeetCode】92. Reverse Linked List II(C++)

【LeetCode】92. Reverse Linked List II(C++)

地址: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是要反轉的部分之前的結點
pppn指向當前處理的兩個結點,pp在左,pn在右
pr是翻轉後的尾節點
cnt是需要通過pppn處理的次數

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; } };