【LeetCode 92】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

思路

設了一個頭結點,m==1時,方便。

代碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if (m == n) return head;
        ListNode* pHead = new ListNode(0);
        pHead->next = head;
        int pos = 1;
        ListNode* st = pHead;
        ListNode* pre = st->next;
        while(pos < m) {
            pre = pre->next;
            st = st->next;
            pos++;
        }
        
        ListNode* cur = pre->next;
        while(pos < n) {
            ListNode* nxt = cur->next;
            cur->next = pre;
            pre = cur;
            cur = nxt;
            pos++;
        }
        
        ListNode* tmp = st->next;
        st->next = pre;
        tmp->next = cur;
        return pHead->next;
    }
}; 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章