lintcode-medium-Reorder List

Posted 哥布林工程师

tags:

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

Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln

reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

 

Example

Given 1->2->3->4->null, reorder it to 1->4->2->3->null.

Challenge

Can you do this in-place without altering the nodes‘ values?

 

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: void
     */
    public void reorderList(ListNode head) {  
        // write your code here
        
        if(head == null || head.next == null || head.next.next == null)
            return;
        
        ListNode slow = head;
        ListNode fast = head;
        
        while(fast != null && fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        
        ListNode head2 = slow.next;
        slow.next = null;
        
        head2 = reverse(head2);
        
        ListNode p1 = head;
        ListNode p2 = head2;
        ListNode p1_next = head.next;
        ListNode p2_next = head2.next;
        
        while(p1_next != null && p2_next != null){
            p1.next = p2;
            p2.next = p1_next;
            p1 = p1_next;
            p2 = p2_next;
            
            p1_next = p1_next.next;
            p2_next = p2_next.next;
        }
        p1.next = p2;
        p2.next = p1_next;
        
        return;
    }
    
    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-Reorder List的主要内容,如果未能解决你的问题,请参考以下文章

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

r plotly 3d曲面图问题

第四周—深层神经网络

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

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

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