92. Reverse Linked List II

走远了吗. 提交于 2020-02-05 16:05:01

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null || head.next==null) return head;
        ListNode cur = head, pre = null;
        while(m>1){
            pre = cur;
            cur = cur.next;
            --n;
            --m;
        }
        ListNode con = pre, tail = cur;
        while(n>0){
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
            --n;
        }
        if(con!=null){
            con.next = pre;
        }else{
            head = pre;
        }
        tail.next = cur;
        return head;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!