zoukankan      html  css  js  c++  java
  • 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

    AC 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* dummy = new ListNode(0);
            ListNode* pre = new ListNode(0);
            ListNode* cur = new ListNode(0);
            dummy->next = head;
            pre = dummy;
            cur = dummy->next;
            for (int i = 1; i < m; ++i) {
                pre = pre->next;
                cur = cur->next;
            }
            for (int i = 0; i < n-m; ++i) {
                ListNode* temp = cur->next;
                cur->next = temp->next;
                temp->next = pre->next;
                pre->next = temp;
            }
            return dummy->next;
        }
    };
    

    Runtime: 0 ms, faster than 100.00% of C++ online submissions for Reverse Linked List II.

    core code:

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

    step 1:

      

    1  2  3  4  5

    pre

      cur

         temp

    cur->next = temp->next;  2  ->  4
    temp->next = pre->next;  3  ->  2
    pre->next = temp;      1  ->  3

       

    step 2:

    1  2  3  4  5

    pre

      cur

             temp

    cur->next = temp->next;  2  ->  5
    temp->next = pre->next;  4  ->  3
    pre->next = temp;      1  ->  4
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    LeetCode刷题7——数字的补数
    Leetcode刷题6—不同路径
    Leetcode刷题5—最大子序和
    LeetCode刷题4——子集
    LeetCode刷题3——位1的个数
    LeetCode刷题2——颠倒二进制位
    小鸡啄米问题求解
    weavenet
    为系统守护进程预留计算资源
    PolicyRouting (ip rule)
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9867143.html
Copyright © 2011-2022 走看看