首页 > 其他 > 详细

92. Reverse Linked List II 翻转链表II

时间:2020-09-13 11:40:51      阅读:66      评论:0      收藏:0      [点我收藏+]

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* prem = dummy;
        //先找到第m个以及前一个
        for(int i=0;i<m-1;i++){
            prem = prem->next;
        }
        ListNode* cur = prem->next;
        //找到第n个以及后一个.
        ListNode* pren = dummy;
        for(int i=0;i<n;i++){
            pren = pren->next;
        }
        //翻转
        prem->next = reverse(cur,pren->next);
        //返回
        return dummy->next;
    }
    
    //@last 翻转链表的最后一个节点的后一个节点
    ListNode* reverse(ListNode* head,ListNode* last){
        ListNode *pre = last,*cur = head;
        while(cur != last){
            ListNode* Next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = Next;
        }
        return pre;
    }
    
};

 

92. Reverse Linked List II 翻转链表II

原文:https://www.cnblogs.com/wsw-seu/p/13660622.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!