码迷,mamicode.com
首页 > 其他好文 > 详细

92. Reverse Linked List II

时间:2018-10-28 22:07:14      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:head   cpp   init   ebe   ast   out   code   step   mis   

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

 

92. Reverse Linked List II

标签:head   cpp   init   ebe   ast   out   code   step   mis   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/9867143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!