美文网首页
92. Reverse Linked List II

92. Reverse Linked List II

作者: evil_ice | 来源:发表于2016-12-27 20:30 被阅读4次

题目92. Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head == null || head.next == null){
            return head;
        }
        
        if(m == n){
            return head;
        }
        
        ListNode tempHead = new ListNode(1);
        tempHead.next = head;
        
        ListNode reverseHead = null;
        ListNode tail = null;
        ListNode node = tempHead;
        ListNode tempNode = null;
        int curNum = 0;
        while(node != null){
            tempNode = node.next;
            if(curNum == (m - 1)){
                reverseHead = node;
                tail = reverseHead;
            }else if(curNum >= m && curNum <= n){
                node.next = reverseHead.next;
                reverseHead.next = node;
                tail = tail.next;
            }else if(curNum > n){
                break;
            }
            node=tempNode;
            curNum ++;
        }
        tail.next = node;
        return tempHead.next;
    }
}

相关文章

网友评论

      本文标题:92. Reverse Linked List II

      本文链接:https://www.haomeiwen.com/subject/diuevttx.html