算法系列——Reorder List

来源:互联网 发布:淘宝商城包 编辑:程序博客网 时间:2024/06/05 07:23

题目描述

Given a singly linked list L: L0?L1?…?Ln-1?Ln,
reorder it to: L0?Ln?L1?Ln-1?L2?Ln-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.合并两个链表

程序实现

public class Solution {    public void reorderList(ListNode head) {        if(head==null||head.next==null)            return;        //快慢指针分割链表        ListNode slow=head;        ListNode fast=head;        while(fast.next!=null&&fast.next.next!=null){            slow=slow.next;            fast=fast.next.next;        }        fast=slow.next;        slow.next=null;        slow=head;        fast=reverse(fast);        merge(slow,fast);    }    private ListNode reverse(ListNode head){        if(head==null||head.next==null)            return head;        ListNode pre=null;        ListNode cur=head;        while(cur!=null){            ListNode next=cur.next;            cur.next=pre;            pre=cur;            cur=next;        }        return pre;    }    private ListNode merge(ListNode p1,ListNode p2){        if(p1==null)            return p2;        if(p2==null)            return p1;        ListNode head=p1;        while(p1!=null){            if(p2!=null){                ListNode p1Next=p1.next;                p1.next=p2;                ListNode p2Next=p2.next;                p2.next=p1Next;                p1=p1Next;                p2=p2Next;            }            else                break;        }        return head;    }}