leetcode reorder-list(java实现)

来源:互联网 发布:访问网络电脑需要密码 编辑:程序博客网 时间:2024/05/16 04:49

原题:

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}.


分析:

思路是将链表分为前后两部分,将后面的部分逆置后依次对应插入。具体实现中先采用快慢指针找到链表的中点,将链表分为两部分。我的代码中用快慢指针找中点时,没有做额外的处理,合并列表时也没有多余的操作,所以在最前面需要将只有两个元素(即head.next.next==null)的情况提前考虑,否则会报错。

代码如下:

public class Solution {    public void reorderList(ListNode head) {        if(head==null || head.next==null || head.next.next==null) return ;        ListNode head2 = null;        ListNode slow = head;        ListNode fast = head;        while(fast!=null && fast.next!=null){        slow = slow.next;        fast = fast.next.next;        if(slow == fast){        break;        }        }        head2 = reverseList(slow.next);        slow.next = null;        while(head!=null && head2!=null){        ListNode p1 = head.next;        ListNode p2 = head2.next;        head.next = head2;        head2.next = p1;        head = p1;        head2 = p2;        }    }     public static ListNode reverseList(ListNode head){    ListNode cur = null;    ListNode p = head.next;    if(p == null) return head;    cur = head;    cur.next = null;    while(p!=null){    ListNode tmp = cur;    cur = p;    p = p.next;    cur.next = tmp;    }    return cur;    }}


0 0
原创粉丝点击