92. Reverse Linked List II

problem description

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ mn ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

algorithm thought

首先找到待旋转的节点,然后就是一个旋转链表问题了

code

/**
 * 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) {
        ListNode* newhead=new ListNode(-1);
        newhead->next=head;
        ListNode* pre=newhead;
        while(n--,--m)
            pre=pre->next;
        ListNode* tmp=pre->next;
        while(n--){
            ListNode* move=tmp->next;
            tmp->next=move->next;
            move->next=pre->next;
            pre->next=move;
        }
        return newhead->next;
    }
};

algorithm analysis

对链表进行一次遍历,转置,循环中操作都是O(1),最后时间复杂度O(n)

Last updated