您的位置:首页 > 编程语言 > Go语言

Reorder List

2014-01-27 08:33 441 查看


Reorder List

 Total Accepted: 4553 Total
Submissions: 24580My Submissions

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

solution:
先对分,然后把后半部分 reverse, 接着挨个插入前半部分

/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null) return;
ListNode slow = head, fast = head.next;
while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
}
ListNode mid = slow.next;
slow.next = null;
mid = reverseList(mid,null);
while(head!=null && mid!=null){
ListNode nextMid = mid.next;
mid.next = head.next;
head.next = mid;
head = head.next.next;
mid = nextMid;
}
}
private ListNode reverseList(ListNode head, ListNode pre){
if(head == null) return pre;
ListNode temp = head.next;
head.next = pre;
return reverseList(temp, head);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode algorithm