Skip to content

Latest commit

 

History

History
54 lines (42 loc) · 1.67 KB

0092. 反转链表 II [Medium] [Reverse Linked List II].md

File metadata and controls

54 lines (42 loc) · 1.67 KB

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

题目:将链表中的第mn个结点反转。

思路:参考discuss。将第m-1个结点记为pre,第m个结点记为cur,那么反转即将第m+1至第n个结点依次插入prepre->next中。precur未改变,只改变了pre->nextcur->next。如将第m+1结点then=cur->next插入prepre->next中时,先记录m+2个点的位置,即cur->next = then->next。然后将then->next指向pre->next,最后pre->next指向then

工程代码下载

/**
 * 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* dummy = new ListNode(0);
        ListNode* pre = dummy;
        pre->next = head;

        for(int i = 1; i < m; ++i){
            if(pre != nullptr)
                pre = pre->next;
        }

        ListNode* cur = pre->next;
        for(int i = m; i < n; ++i){
            ListNode* next = cur->next;
            cur->next = next->next;
            next->next = pre->next;
            pre->next = next;
        }

        return dummy->next;
    }
};