Leetcode 92. Reverse Linked List II

    xiaoxiao2021-03-26  26

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

    For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4,

    return 1->4->3->2->5->NULL.

    Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.

    s思路: 1. 反转链表。一种方法,先定位reverse开始位置,然后后面的节点插入到这个位置之前。直到插入完。reverse一般需要三个指针, 2. 由于有可能从第一个节点就reverse,那么头节点就会改变。因此,还是需要用dummy或pointer-to-pointer.

    上图,指向指针的指针先移动m步后固定位置,然后p的下一个节点就是反转之后的最右边节点,所以后面的节点都插入到p节点和p的下一个之间。

    //方法1: class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { // ListNode** p=&head; n=n-m; while(--m){ p=&((*p)->next); } ListNode* r=*p; while(n--){ ListNode* pnext=r->next->next; ListNode* pre=*p; (*p)=r->next; (*p)->next=pre; r->next=pnext; } return head; } };
    转载请注明原文地址: https://ju.6miu.com/read-650305.html

    最新回复(0)