Reorder List
来源:互联网 发布:iphone蜂窝数据用户名 编辑:程序博客网 时间:2024/06/06 06:00
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}
.
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
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- 在安装Ubuntu的MacBook上更改Apple 键盘模式
- 最小边割集
- Leetcode Power of Two/Three/Four
- Leetcode Path Sum
- Leetcode Remove Duplicates from Sorted List
- Reorder List
- 重建控制文件后,各文件(datafile、control file、redo log)中scn的关系
- Leetcode Odd Even Linked List
- Leetcode Binary Tree Maximum Path Sum
- IOS控件总是看不见。
- Leetcode Maximal Rectangle
- Leetcode 3Sum Closest
- Leetcode Populating Next Right Pointers in Each Node
- Leetcode Length of Last Word