lintcode-medium-Reverse Linked List II

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Reverse Linked List II相关的知识,希望对你有一定的参考价值。

Reverse a linked list from position m to n.

 

Notice

Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.

Example

Given 1->2->3->4->5->NULL, m = 2 and n = 4, return1->4->3->2->5->NULL.

Challenge

Reverse it in-place and in one-pass

 

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param ListNode head is the head of the linked list 
     * @oaram m and n
     * @return: The head of the reversed ListNode
     */
    public ListNode reverseBetween(ListNode head, int m , int n) {
        // write your code
        
        ListNode fakehead = new ListNode(0);
        fakehead.next = head;
        ListNode end1 = fakehead;
        
        for(int i = 1; i < m; i++)
            end1 = end1.next;
        
        ListNode head2 = end1.next;
        end1.next = null;
        
        ListNode end2 = head2;
        
        for(int i = 0; i < n - m; i++)
            end2 = end2.next;
        
        ListNode head3 = end2.next;
        end2.next = null;
        head2 = reverse(head2);
        
        end1.next = head2;
        end2 = head2;
        while(end2.next != null)
            end2 = end2.next;
        end2.next = head3;
        
        return fakehead.next;
    }
    
        public ListNode reverse(ListNode head){
        if(head == null || head.next == null)
            return head;
        
        ListNode prev = head;
        ListNode curr = head.next;
        ListNode next = head.next.next;
        
        head.next = null;
        
        while(next != null){
            curr.next = prev;
            prev = curr;
            curr = next;
            next = next.next;
        }
        
        curr.next = prev;
        
        return curr;
    }
}

 

以上是关于lintcode-medium-Reverse Linked List II的主要内容,如果未能解决你的问题,请参考以下文章

如何循环遍历行,然后在每行循环遍历列直到找到NA,然后提取前一列的值

r plotly 3d曲面图问题

第四周—深层神经网络

超过常规语言 L 和 D(L)

如果 L 和 L 补码是递归可枚举的,那么为啥 L 不能是正则语言?

神经网络与深度学习笔记(番外)反向传播推导