Reorder List

来源:互联网 发布:iphone蜂窝数据用户名 编辑:程序博客网 时间:2024/06/06 06:00

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


Difficulty: Medium


/** * 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 || head.next.next == null) return;        ListNode ans = head;        int count = 0; ListNode curr = head;        while(curr != null){            count++;            curr = curr.next;        }        curr = head;        ListNode pre = head, next = null;        for(int i = 0; i < count/2 + count%2; i++){            pre = curr;            curr = curr.next;        }        pre.next = null;        pre = curr; next = curr.next; curr.next = null;        while(next != null){            curr = next;            next = curr.next;            curr.next = pre;            pre = curr;        }        ListNode headNext = null;        ListNode currNext = null;        while(curr != null){            headNext = head.next;            currNext = curr.next;            head.next = curr;            curr.next = headNext;            head = headNext;            curr = currNext;                    }        head = ans;        return;    }}


0 0
原创粉丝点击