zoukankan      html  css  js  c++  java
  • [LeetCode] Reverse Linked List II

    The basic idea is as follows:

    1. Create a new_head that points to head and use it to locate the immediate node before them-th (notice that it is 1-indexed) node pre;
    2. Set cur to be the immediate node after pre and at each time move the immediate node after cur (named move) to be the immediate node after pre. Repeat it for n - m times.
     1 class Solution {  
     2 public:
     3     ListNode* reverseBetween(ListNode* head, int m, int n) {
     4         ListNode* new_head = new ListNode(0);
     5         new_head -> next = head;
     6         ListNode* pre = new_head;
     7         for (int i = 0; i < m - 1; i++)
     8             pre = pre -> next;
     9         ListNode* cur = pre -> next;
    10         for (int i = 0; i < n - m; i++) {
    11             ListNode* move = cur -> next; 
    12             cur -> next = move -> next;
    13             move -> next = pre -> next;
    14             pre -> next = move;
    15         }
    16         return new_head -> next;
    17     }
    18 };
  • 相关阅读:
    Codeforces 1354C2
    Codeforces 1354C1
    Codeforces 1355C
    Codeforces 1353D
    Codeforces 1352
    Codeforces 1351C
    Codeforces 1344B/1345D
    Codeforces 1342D
    Codeforces 1340B/1341D
    Codeforces 1343D
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4777400.html
Copyright © 2011-2022 走看看