leetcode--Reorder List

来源:互联网 发布:指甲油品牌知乎 编辑:程序博客网 时间:2024/06/08 00:35

Given a singly linked list L: L0L1→…→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}.

/** * 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 slow = head;ListNode fast = head;while(slow!=null&&fast!=null&&fast.next!=null){slow = slow.next;fast = fast.next.next;}ListNode mid = slow.next;ListNode last = mid;ListNode pre = null;while(last!=null){ListNode t = last.next;last.next = pre;pre = last;last = t;}slow.next = null;while(head!=null&&pre!=null){ListNode t = head.next;head.next = pre;pre = pre.next;head.next.next = t;head = t;}    }}

0 0
原创粉丝点击