leetcode reorder-list(Java)

leetcode题目

reorder-list

题目描述

 * Given a singly linked list L: L 0→L 1→…→L n-1→L n,
 * reorder it to: L 0→L n →L 1→L n-1→L 2→L n-2→…
 * You must do this in-place without altering the nodes' values.
 * For example,
 * Given{1,2,3,4}, reorder it to{1,4,2,3}.

思路

 * 1、找到链表的中间节点
 * 2、断链表为两个链表
 * 3、反转第二个链表
 * 4、重组两个链表为一个链表(交替连接两个链表的元素)

代码

package com.leetcode.list;

/**
 * 题目:
 * reorder-list
 * 
 * 题目描述:
 * Given a singly linked list L: L 0→L 1→…→L n-1→L n,
 * reorder it to: L 0→L n →L 1→L n-1→L 2→L n-2→…
 * You must do this in-place without altering the nodes' values.
 * For example,
 * Given{1,2,3,4}, reorder it to{1,4,2,3}.
 */
public class ReorderList {

	static class ListNode{
		 int val;
		 ListNode next;
		 ListNode(int x) {
		     val = x;
		     next = null;
		 }
        @Override
        public String toString() {
            if (this.next == null) {
                return String.valueOf(this.val);
            }
            return this.val + "->" + this.next.toString();
        }
	}
	
	/**
	 * 思路:
	 * 1、找到链表的中间节点
	 * 2、断链表为两个链表
	 * 3、反转第二个链表
	 * 4、重组两个链表为一个链表(交替连接两个链表的元素)
	 * 
	 * @param head 头节点
	 */
    public void reorderList(ListNode head) {
    	// 1、链表的长度不超过2直接返回
    	if (head == null || head.next == null || head.next.next == null) {
    		return;
    	}
    	
    	// 2、获取链表的中间节点
    	ListNode mid = getMid(head);
    	
    	// 3、断开链表为两个链表
    	// 第二个链表,头节点为mid.next
    	ListNode second = mid.next;
    	// 断开链表
    	mid.next = null;
    	// 反转链表
    	second = reverse(second);
    	
    	// 4、组合新的两个链表为一个链表
    	// 第一个链表头节点为head,尾节点为mid
    	ListNode first = head;
    	
    	while (first != null && second != null) {
    		ListNode firstNext = first.next;
    		ListNode secondNext = second.next;
    		first.next = second;
    		second.next = firstNext;
    		first = firstNext;
    		second = secondNext;
    	}
    }
    
    private ListNode getMid(ListNode head) {
    	ListNode fast = head;
    	ListNode slow = head;
    	while (fast != null && fast.next != null) {
    		fast = fast.next.next;
    		slow = slow.next;
    	}
    	return slow;
    }

	private ListNode reverse(ListNode head) {
		ListNode newHead = null;
		ListNode cur = head;
		while (cur != null) {
			ListNode tmp = cur.next;
			// 断开链表
			cur.next = newHead;
			newHead = cur;
			cur = tmp;
		}
		return newHead;
	}
    
	public static void main(String[] args) {
		ListNode head = createTestLinkedList();
		ListNode newHead = new ListNode(13);
		newHead.next = head;
		System.out.println(newHead);
		new ReorderList().reorderList(newHead);
		System.out.println(newHead);
	}
	
    private static ListNode createTestLinkedList() {
    	ListNode head = new ListNode(0);
    	ListNode curNode = head;
        for (int i = 1; i < 10; i++) {
            curNode.next = new ListNode(i);
            curNode = curNode.next;
        }
        return head;
    }

}

猜你喜欢

转载自blog.csdn.net/zangdaiyang1991/article/details/89344887