Reorder List

来源:互联网 发布:淘宝领的话费券在哪 编辑:程序博客网 时间:2024/06/05 07:34

链表基本功

1. 找到中点;

2. 对链表后半部分反转;

3. 将前半部分和后半部分拼接

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public void reorderList(ListNode head) {        if (head == null || head.next == null) {return;}ListNode fn = head.next.next, sn = head;while (fn != null && fn.next != null) {sn = sn.next;fn = fn.next.next;}if (fn != null) {sn = sn.next;}ListNode rightHalf = reverse(sn.next);sn.next = null;while (rightHalf != null) {ListNode temp1 = head.next;head.next = rightHalf;ListNode temp2 = rightHalf.next;rightHalf.next = temp1;head = temp1;rightHalf = temp2;}    }private ListNode reverse(ListNode node) {ListNode prev = null;while (node != null) {ListNode temp = node.next;node.next= prev;prev = node;node = temp;}return prev;}}

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.



0 0